💛TypeScript对象与接口

本文最后更新于:2023年7月28日 凌晨

使用interface声明接口

声明对象

interface可用于声明对象类型 TS不检查属性的序列

1
2
3
4
5
6
7
8
9
10
11
interface Message {
age: number;
name: string;
isMale: boolean;
}

const aboutMe: Message = {
age: 20,
isMale: true, // 交换顺序不会报错
name: 'Jonathan',
}

可选属性

使用?:表示为可选参数

1
2
3
4
5
6
interface Message {
name: string;
age: number;
isMale: boolean;
birth?: string;
}

只读属性

readonly声明属性只读(不可重写)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Message {
age: number;
name: string;
readonly isMale: boolean;
}

const aboutMe: Message = {
age: 20,
isMale: true,
name: 'Jonathan',
}

aboutMe.isMale = false
// > Cannot assign to 'isMale' because it is a read-only property.

任意属性

用接口声明一个必须有nameage的类型,且可以增加任意其它属性

1
2
3
4
5
6
7
8
9
10
11
12
13
interface Person {
name: string;
age: number;
[id: string]: any;
// 将any改为其它类型可约束任意属性的类型
}

const man: Person = {
name: 'Jonathan',
age: 20,
isMale: true,
nationality: 'CN'
}

接口继承

参考文档:


💛TypeScript对象与接口
https://qingshaner.com/TypeScript对象与接口/
作者
清山
发布于
2022年4月22日
许可协议