What is the difference between interface and type in Typescript?

type alias type

Type aliases are used to give a new name to a type. Use type to create a type alias.

Type aliases can be used not only to represent basic types, but also to represent object types, union types, tuples, and intersections.

Let's look at some examples:

type userName = string; // 基本类型
type userId = string | number; // 联合类型
type arr = number[];  
// 对象类型
type Person = {
    
    
    id: userId; // 可以使用定义类型
    name: userName;
    age: number;
    gender: string;
    isWebDev: boolean;
};
// 范型
type Tree<T> = {
    
     value: T };
const user: Person = {
    
    
    id: "901",
    name: "椿",
    age: 22,
    gender: "女",
    isWebDev: false,
};
const numbers: arr = [1, 8, 9];

interfaceinterface

An interface is another way of naming a data structure (such as an object); unlike type, interface is limited to describing object types .

The declaration syntax for interfaces also differs from the declaration syntax for type aliases.

Let's rewrite the above type alias Person as an interface declaration:

interface Person {
    
    
    id: userId;
    name: userName;
    age: number;
    gender: string;
    isWebDev: boolean;
}

Similarities between interface and type

Both Object and Function can be described

Both can be used to describe objects or functions, but the syntax is different:

Type

type Point = {
    
    
  x: number;
  y: number;
};
type SetPoint = (x: number, y: number) => void;

Interface

interface Point {
    
    
  x: number;
  y: number;
}
interface SetPoint {
    
    
  (x: number, y: number): void;
}

Both can be inherited

Both interface and type can be inherited.

Another thing to note is that interfaces and type aliases are not mutually exclusive.

Type aliases can inherit interfaces and vice versa.

There are only slight differences in the implementation form.

interface inherits interface
interface Person{
    
    
    name:string
}
interface Student extends Person {
    
     stuNo: number }
ninterface inherits type
type Person{
    
    
    name:string
}
interface Student extends Person {
    
     stuNo: number }
type inherit type
type Person{
    
    
    name:string
}
type Student = Person & {
    
     stuNo: number }
type inherits interface
interface Person{
    
    
    name:string
}
type Student = Person & {
    
     stuNo: number }
implementimplements

Classes can implement interface and type (except union types)

interface ICat{
    
    
    setName(name:string): void;
}
class Cat implements ICat{
    
    
    setName(name:string):void{
    
    
        // todo
    }
}
// type  
type ICat = {
    
    
    setName(name:string): void;
}
class Cat implements ICat{
    
    
    setName(name:string):void{
    
    
        // todo
    }
}

The special case mentioned above is that a class cannot implement a union type. What does this mean?

type Person = {
    
     name: string; } | {
    
     setName(name:string): void };
// 无法对联合类型Person进行实现
// error: A class can only implement an object type or intersection of object types with statically known members.
class Student implements Person {
    
    
  name= "张三";
  setName(name:string):void{
    
    
        // todo
    }
}

The difference between interface and type

Define basic type aliases

Type can define basic type aliases, but interface cannot, such as:

type userName = string
type stuNo = number
...

Declare union type

type can declare a union type, for example:

type Student = {
    
    stuNo: number} | {
    
    classId: number}

declare tuple

type can declare a tuple type:

type Data = [number, string];

The above are all things that type can do, but interface can’t do. Next, let’s talk about what type can’t do.

Statement merge

If you declare an interface with the same name multiple times, TypeScript will merge them into a single declaration and treat them as one interface. This is called declaration merging .

For example:

interface Person {
    
     name: string }
interface Person {
    
     age: number }
let user: Person = {
    
    
    name: "Tolu",
    age: 0,
};

In this case, if it is type, an error will be reported if Person is used repeatedly:

type Person {
    
     name: string };  
// Error: 标识符“Person”重复。ts(2300)
type Person {
    
     age: number }

Index signature issue

If you often use TypeScript, you must have encountered similar errors:

Type 'xxx' is not assignable to type 'yyy'
Index signature is missing in type 'xxx'.

Summarize

The official recommendation is to use interface. If other requirements cannot be met, use type.

But in fact, because union types and intersection types are very commonly used, it is inevitable to use a large number of types. Some complex types also need to be assembled to form type aliases for use.

Therefore, if you want to keep the code unified, you can still choose to use type. Through the above comparison, type aliases can actually cover most interface scenarios.

For more details, please search " " on WeChat前端爱好者 and click me to view .

Reference documentation:

  • https://www.jb51.net/article/243639.htm

Guess you like

Origin blog.csdn.net/BradenHan/article/details/134820173
Recommended