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 @   胸怀丶若谷  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
历史上的今天:
2022-04-27 Node: Module not found: Can't resolve 'xlsx'
2020-04-27 判断字符是否以某个字符开头和结尾
点击右上角即可分享
微信分享提示

目录导航