There are two ways to define types in TypeScript

  • 1. Interface: Only object types can be constrained
  • 2. Type alias: declaratively defines composite types, cross types, and primitive types

The same

  • Can constrain an object or a 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
Copy the code
  • 2. Both allow extends

Interface and Type can both extend, and they are not independent of each other. That is to say, interface extends Type, and type extends interface. The effect is similar, but the syntax is different.

// interface extends interface interface Name{ name: string } interface Users extends Name{ age: // 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}Copy the code

The difference between

  • Type Specifies basic type aliases, union types, primitives, and other types
// Alias type Name = string; // Interface Dog {wong()} interface Cat {miao(); } type Pet = Dog | Cat; // Specify the type of each position in the array type PetList = [Dog, Pet];Copy the code
  • 2, The type statement can also use typeof to obtain instance type assignment
// when you want to get the typeof a variable, use typeof let div = document.createelement ('div'); type B = typeof div;Copy the code
  • 3, interface can declare merge
interface User { name: string; age: number; } interface User { sex: string; } // The User interface is: {name: string; age: number; sex: string; }Copy the code