[TypeScript] interface and object type

In TypeScript, an interface (Interface) is a convention used to define the structure of an object, which describes the properties and methods that the object should have. Interfaces provide a definitional constraint that enables you to explicitly specify the shape and type of an object when writing code. Interfaces are often used in development to define the structure of objects, the implementation of classes, and the parameters and return values ​​of functions.

Here is a simple example showing how to use interfaces to define the structure of an object:

interface Person {
    
    
  // 不能多属性,也不能少属性
  firstName: string;
  lastName: string;
  // age: number;
}
// 也可以写多个重名,属性相加
interface Person {
    
    
  // 不能多属性,也不能少属性
  age: number;
}

const person: Person = {
    
    
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};

In the above example, we defined an Personinterface called which contains the firstName, lastNameand ageproperties. Then, we create a personobject that conforms to the structure of this interface.

Other usages, examples are as follows:

interface xxx extends x {
    
    
  name: string,
  // readonly 修饰为只读,不可修改
  readonly id:number,
  // 索引签名,随便定义下面属性,它的值代表interface里面所有值,所以一般为 any
  [propName: string]: any
}
// extends 用于接口继承
interface x {
    
    
  xx:string
}

let a:xxx = {
    
    
  name: 'xxx',
  id: 1,
  age: 18,
  sex: '男',
  xx: 'xxx'
}

// 定义函数类型
interface Fn {
    
    
  (a: number): number[]
}
const fn: Fn = (a) => {
    
    
  return [1, 2, 3]
}

Guess you like

Origin blog.csdn.net/XiugongHao/article/details/132315286