【TypeScript】接口和对象类型

在 TypeScript 中,接口(Interface)是一种用于定义对象结构的约定,它描述了对象应该具有的属性和方法。接口提供了一种定义约束,使你能够在编写代码时明确地指定对象的形状和类型。接口在开发中常用于定义对象的结构、类的实现以及函数的参数和返回值。

以下是一个简单的示例,展示如何使用接口定义一个对象的结构:

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

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

在上面的示例中,我们定义了一个名为 Person 的接口,它包含了 firstNamelastNameage 属性。然后,我们创建了一个符合该接口结构的 person 对象。

其他用法,实例如下:

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]
}

猜你喜欢

转载自blog.csdn.net/XiugongHao/article/details/132315286
今日推荐