你需要知道 TypeScript 的那些事<四>
写在前面:本次 ts 系列文章共4篇,从入门到"入土"系列,本文为第四篇,且本文仅作为学习笔记。
我与春风皆过客,你携秋水揽星河。
上回说到:TS 是 JS 的超集(包含关系)
;TS 中对于变量、函数接收参数和返回参数等都有严格的类型判断
;TS 中 type 类型别名
和 interface 接口
的区别,大体上没有区别,但是在扩展、继承等方面还是有些差异;详情请查看:第一篇链接;TS 中类型断言(as)和 类型收窄(in\typeof\instanceof)的用法以及文字类型和枚举类型示例;详情请查看:第二篇链接;TS 中函数相关约束、泛型以及函数重载;详情请查看:第三篇链接;
本文主要内容:对象相关约束、接口继承、对象的泛型
本文阅读时间大约为5分钟,请听笔者娓娓道来。
对象相关约束
举个🌰
function greet(perseon: { name: string; age: number }) {
return "Hello " + person.name;
}
也可以通过接口或类型别名
举个🌰
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
return "Hello " + person.name;
}
type Person = {
name: string;
age: number;
};
function greet(perseon: Person) {
return "Hello " + person.name;
}
属性修饰符
对象类型中的每个属性可以指定两个事项: 类型、属性是否可选以及是否可以将属性写入。
可选属性
在这些情况下,我们可以通过添加一个问号(?)将这些属性标记为可选的直到他们的名字结束。
举个🌰
interface PaintOptions {
shape: Shape;
xPos?: number;
yPos?: number;
}
function paintShape(opts: PaintOptions) {
// ...
}
const shape = getShape();
paintShape({ shape });
paintShape({ shape, xPos: 100 });
paintShape({ shape, yPos: 100 });
paintShape({ shape, xPos: 100, yPos: 100 });
在本例中,xPos 和 yPos 都被认为是可选的。我们可以选择提供其中任何一个,因此上面对 paintShape 的每个调用都是有效的。所有可选性真正说的是,如果属性是设置的,它最好有一个特定的类型。
索引签名
可选属性是可传也可不传,但是如果未知属性名的话,可以通过以下这种方式
interface StringObj {
[index: string]: number;
}
举个🌰
// key 值要是 string 类型
// value 值要是 number 类型
const str:StringObj = {
age: 18
}
修改 value 是联合类型 number | string
interface StringObj {
[index: string]: number | string;
}
举个🌰
// key 值要是 string 类型
// value 值要是 number 类型
const str:StringObj = {
name:'zs',
age: 18,
sex:'男',
123:456 //报错 key 要为 string
}
扩展类型
使用extends
继承,可以多个。
举个🌰
interface Father {
father_x_chromosome: string;
father_y_chromosome: string;
}
interface Mather {
mother_x_chromosome: string;
}
interface Son extends Father, Mather {}
const son: Son = {
mother_x_chromosome: x,
father_y_chromosome: y
};
泛型对象类型
上篇,咱们在函数中使用了泛型,在对象中也可以适用。
举个🌰
interface Box<T> {
name: T;
}
type Boxs<T> = {
name: T;
};
const myBox:Box<string> = {name:'123'}
const myBox:Box<number> = {name:123}
const myBox:Boxs<string> = {name:'123'}
const myBox:Boxs<number> = {name:123}
总结
TypeScript 的阶段性总结到此为止了,有些部分没有记录。我认为在工作中实践我们学到的知识,才会更深刻的理解。切勿停留在表面,否则总是 好像什么都会,好像什么又都不会。加油吧!前端攻城狮!