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

Monitor the size change of a DOM element through iframe

A common problem encountered during the developme...

Docker starts MySQL configuration implementation process

Table of contents Actual combat process Let's...

Ubuntu 18.04 disable/enable touchpad via command

In Ubuntu, you often encounter the situation wher...

A brief discussion on the problem of forgotten mysql password and login error

If you forget your MySQL login password, the solu...

React Fiber structure creation steps

Table of contents React Fiber Creation 1. Before ...

How to configure MySQL8 in Nacos

1. Create the MySQL database nacos_config 2. Sele...

How to configure nginx+php+mysql in docker

First, understand a method: Entering a Docker con...

Two common solutions to html text overflow display ellipsis characters

Method 1: Use CSS overflow omission to solve The ...

A brief introduction to Linux environment variable files

In the Linux system, environment variables can be...

Discuss the development trend of Baidu Encyclopedia UI

<br />The official version of Baidu Encyclop...

Detailed explanation of data type issues in JS array index detection

When I was writing a WeChat applet project, there...

MySQL stored procedure method example of returning multiple values

This article uses an example to describe how to r...

Docker practice: Python application containerization

1. Introduction Containers use a sandbox mechanis...