Typescript difference in the interface and type of

Same point:

You can describe an object or function

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

interface SetUser {
 (name: string, age: number): void;
}

// type
type User = {
 name: string
 age: number
};

type SetUser = (name: string, age: number): void;

Allow expansion of (the extends)
interface and type can be expanded, and the two are not independent of each other, that can interface extends type, type can also extends interface. Although the effect is almost, but two different syntax.

// interface extends interface
interface Name { 
 name: string; 
}
interface User extends Name { 
 age: number; 
}
// type extends type
type Name = { 
 name: string; 
}
type User = Name & { age: number };
// interface extends type
type Name = { 
 name: string; 
}
interface User extends Name { 
 age: number; 
}
// type extends interface
interface Name { 
 name: string; 
}
type User = Name & { 
 age: number; 
}

difference:

The interface type can not
type can declare type aliases basic types, union types, tuples, etc.

// 基本类型别名
type Name = string

// 联合类型
interface Dog {
 wong();
}
interface Cat {
 miao();
}

type Pet = Dog | Cat

// 具体定义数组每个位置的类型
type PetList = [Dog, Pet]

type typeof statement can also be used to obtain an instance of the type of assignment

// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type B = typeof div

Other Sao operation

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 type can not
interface can declare the merger

interface User {
 name: string
 age: number
}

interface User {
 sex: string
}

/*
User 接口为 {
 name: string
 age: number
 sex: string 
}
*/

In general, if you are unsure when to use interface / type, interface can achieve, to use interface, if you can not use type.

 

 



Author: Micro Zhiyi
link: https: //www.jianshu.com/p/783491d0293f
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Published 229 original articles · won praise 80 · views 410 000 +

Guess you like

Origin blog.csdn.net/qq_34629352/article/details/104949941