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

Things to note when migrating MySQL to 8.0 (summary)

Password Mode PDO::__construct(): The server requ...

View the port number occupied by the process in Linux

For Linux system administrators, it is crucial to...

Tutorial on how to remotely connect to MySQL database under Linux system

Preface I recently encountered this requirement a...

Detailed example of MySQL exchange partition

Detailed example of MySQL exchange partition Pref...

How to migrate the data directory in Docker

Table of contents View Disk Usage Disk Cleanup (D...

js realizes the function of clicking to switch cards

This article example shares the specific code of ...

Detailed explanation of special phenomena examples of sleep function in MySQL

Preface The sleep system function in MySQL has fe...

mysql 5.7.20 win64 installation and configuration method

mysql-5.7.20-winx64.zipInstallation package witho...

How to fix some content in a fixed position when scrolling HTML page

This article mainly introduces how some content i...

How to set up scheduled backup tasks in Linux centos

Implementation Preparation # Need to back up the ...

Summary of 7 pitfalls when using react

Table of contents 1. Component bloat 2. Change th...