Examples of correct use of interface and type methods in TypeScript

Examples of correct use of interface and type methods in TypeScript

Preface

Both interface and type are used to define types, which can be understood as defining shapes. Shape represents a design framework, or in other words, a class of things as long as they have certain characteristics or behaviors. In some languages, such as Java, interfaces are used to define behaviors. If a class implements an interface, it means that the class has a certain behavior or capability, such as writable or readable. Things can be divided by behavior. Interface is widely used in golang, but in TypeScript interface is more like a type shape. TypeScript also provides type for defining types. In fact, there is not much difference between interface and type in TypeScript, but there is still a little difference.

interface

An interface can be used to shape a class, object, or function.

interface Tut{
    title:string
    isComplete:boolean
}

Define an interface interface to represent the Tut type, and then define a variable machineLearningTut of type Tut

const machineLearningTut:Tut = {
    title:"machine learning basic",
    isComplete:true
}

If the machineLearningTut of type Tut does not fully implement the interface definition attributes or methods, a friendly prompt will be given during the compilation phase.

const machineLearningTut:Tut = {
    title:"machine learning basic",
}

Tip: The machineLearningTut of type Tut does not implement the isComplete property declared in the interface.

Property 'isComplete' is missing in type '{ title: string; }' but required in type 'Tut'.ts(2741)

[demo2.ts(3, 5): ]()'isComplete' is declared here.
class VideoTut implements Tut{
    title:string;
    isComplete:boolean;
}

You can also define a class VideoTut to implement the Tut interface

interface Greet{
    (name:string):string
}

const greet:Greet = (name) => `hello ${name}`

You can also define the Greet interface for the shape function, defining the function's parameters and the function's return value type.

interface AdvanceTut extends Tut{
    isFree:boolean
}

const machineLearningTut:AdvanceTut = {
    title:"machine learning basic",
    isComplete:true,
    isFree:true
}

Interfaces can be extended through extend. AdvanceTut is an extension of Tut. If type does not support extend, it can be extended between types.

interface Tut{
    title:string
    isComplete:boolean
}

interface Tut{
    isFree:boolean
}

const machineLearningTut:Tut = {
    title:"machine learning basic",
    isComplete:true,
    isFree:true
}

Two Tuts with the same inteface name are declared in succession. These two Tuts are shown to be in an extended relationship, not an overriding relationship, which is also a feature that type does not have.

type

In fact, the usage of type is similar to that of interface, but type is convenient for types and can be an alias for JavaScript basic types. In fact, type is essentially different from interface. Even if this is explained, you may still need to slowly experience it in practice.

type isComplete = boolean
type title = string
type greet = (name:string)=>string

type Tut = {
    title:string;
    isComplete:boolean
}

const machineLearningTut:Tut = {
    title:"machine learning title",
    isComplete:true
}

type Tut = {
    title:string;
    isComplete:boolean
} & {
    isFree:boolean
}

const machineLearningTut:Tut = {
    title:"machine learning title",
    isComplete:true,
    isFree:true
}

Type can & implement the extension of type

type VideoTut = Tut | {
    isFree:boolean
}

const machineLearningTut:VideoTut = {
    title:"machine learning title",
    isComplete:true,
    isFree:true
}
export type InputProps = {
    type:'text'|'email';
    value:string;
    onChane:(newValue:string)=>void
}

In addition, the front-end and back-end types can also be defined using type. As shown below, multiple basic types can be defined, and these defined types can define new types.

type onChaneType = (newValue:string)=>void

type InputType = 'text'|'email';

type InputValue = string

export type InputProps = {
    type:InputType;
    value:InputValue;
    onChane:onChaneType
}

Appendix: Differences between interface and type

type can declare basic type aliases, union types, tuples, etc.

// Basic type alias type Name = string;

//Union type interface Dog {
    wong()
}
interface Cat {
    miao();
}

type Pet = Dog | Cat;

//Specifically define the type of each position in the array type PetList = [Dog, Pet];

In the type statement, you can also use typeof to obtain the type of the instance for assignment

// When you want to get the type of a variable, use typeof
let div = document.createElement('div');
type B = typeof div;

typeOther tricks

type StringOrNumber = string | number;
type Text = string | { text: string };
type NameLookup = Dictionary<string, Person>;
type Callback<T> = (data: T) => void;
type Pair<T> = [T, T];
type Coordinates = Pair<number>;
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

Interface can declare merge

interface User {
    name: string;
    age: number;
}

interface User {
    sex: string;
}

The User interface is:

{
    name: string;
    age: number;
    sex: string;
}


Summarize

This is the end of this article about the correct use of interface and type in TypeScript. For more content about the use of interface and type in TypeScript, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • What is the difference between interface and type in Typescript?
  • TypeScript interface definition case tutorial
  • What is the difference between type and interface in TypeScript?

<<:  mysql is not an internal command error solution

>>:  Steps to install Pyenv under Deepin

Recommend

30 Tips for Writing HTML Code

1. Always close HTML tags In the source code of p...

Getting started with JavaScript basics

Table of contents 1. Where to write JavaScript 2....

Summary of several implementations of returning to the top in HTML pages

Recently, I need to make a back-to-top button whe...

Parse CSS to extract image theme color function (tips)

background It all started when a classmate in the...

How to install multiple mysql5.7.19 (tar.gz) files under Linux

For the beginner's first installation of MySQ...

Solution to the problem that Docker cannot stop or delete container services

Preface Today, a developer gave me feedback that ...

Axios project with 77.9K GitHub repository: What are the things worth learning?

Table of contents Preface 1. Introduction to Axio...

Tutorial on installing MySQL with Docker and implementing remote connection

Pull the image docker pull mysql View the complet...

How to use http and WebSocket in CocosCreator

Table of contents 1. HttpGET 2. HTTP POST WebSock...

Vue realizes the percentage bar effect

This article shares the specific code of Vue to r...

Node implements search box for fuzzy query

This article example shares the specific code for...

CSS eight eye-catching HOVER effect sample code

1. Send effect HTML <div id="send-btn&quo...

Nginx reverse proxy forwards port 80 requests to 8080

Let's first understand a wave of concepts, wh...