The difference between interface and type in TypeScript

difference 1

  • Both using interface and type are common ways of representing a given data structure.
  • The way it is defined is slightly different.
  • When type is defined, there is an "=" symbol
interface User {
    
    
	name: string,
	age: number
}
type User = {
    
    
	name: string,
	age: number
}

difference 2

  • interface can declare the same interface multiple times. They will be merged together to form an interface definition.
  • type can only be declared once.

interface: can be declared multiple times, and can be reused together in the end;

interface User{
    
    
	name: string
}
interface User{
    
    
	age: number
}
let Person: User = {
    
    
	name: 'myName',
	age: 100
}

type: If you declare again, an error will be reported

type User = {
    
    
	name: string
}
type User = {
    
      // 报错,Throw error: Duplicate identifier
	age: number
}

difference 3

  • The inheritance method is different, the interface is inherited through the extend method, and the type is inherited through the & symbol;

interface

interface PointX {
    
    
    x: number
}
interface Point extends PointX {
    
    
    y: number
}

type

type PointX = {
    
    
    x: number
}
type Point = PointX & {
    
    
    y: number
}

interface and type can extend each other

interface

type PointX = {
    
    
    x: number
}
interface Point extends PointX {
    
    
    y: number
}

type

interface PointX {
    
    
    x: number
}
type Point = PointX & {
    
    
    y: number
}

Notice:

  1. If you want to define a variable type, use type, and if you want to be able to inherit and constrain, use interface.
  2. Use interface if you are the author of a library or create type definitions for an external library. It is convenient for others to extend them too.
  3. If you don't know which to use, it is recommended to use type.

Guess you like

Origin blog.csdn.net/weixin_44684357/article/details/132116784
Recommended