TypeScript:接口

介绍

TypeScript的核心原则之一是对值所有的结构类型进行类型检查。在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义约束。

接口的基本使用

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = { size: 10, label: 'Size 10 Object' };
printLabel(myObj);

可选属性

接口里的属性不全都是必须的。有些只是在某些条件下存在,或者根本不存在。可选属性在给函数传入的参数对象中只有部分属性赋值时很常用.

  • 可选属性使用?:表示
interface SquareConfig {
  color?:string;
  width?: number;
}

示例

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: 'white', area: 100 };
  if (config.color) {
    newSquare.color = config.color;
  }

  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let mySquare = createSquare({ color: 'black' });

只读属性

一些对象属性只能在对象刚刚创建的时候修改器值,你可以再属性名前用readonly来指定只读属性:

interface Point {
    readonly x: number;
    readonly y: number;
}

参考链接

https://www.tslang.cn/docs/handbook/interfaces.html

posted @ 2023-04-27 08:50  胸怀丶若谷  阅读(12)  评论(0编辑  收藏  举报