TypeScript 学习记录–高级类型
交叉类型 (& 与的关系)
合并多个类型为一个,拥有每一个类型的所有成员
interface IPerson {
name: string
}
interface IMen {
age: number
}
interface IChild {
parent: IPerson | null
}
type INike = IPerson & IMen & IChild;
const nike: INike = {
name: 'nike',
age: 20,
parent: null
}
联合类型 (| 或的关系)
type ICount = number | string;
const c: ICount = 90;
const d: ICount = 'www';
可选类型 (?)
function a(count?: number) {
console.log(a)
}
a(); // run
a(2); // run
a('xx'); // 报错
类型别名
给一个类型起一个名字就是类型别名,根接口 interface 很像,一般用作简单类型的 原始值 | 联合类型 | 元组 等
type Name = string | number
// 类型可以有泛型,亦可以在类型中使用自己
type IA<T> = {
value: T,
A: IA<T>
}
- 与接口 interface 的区别,interface 创建了一个新的名字,可以在其他地方使用,类型并不创建新的名字
- 类型别名不能被 extends 和 implements
- 类型别名不能出现在声明的右侧
字面量类型
数字 | 字符串
type IA = 'xxx' | 222
this 类型
class Parent {
public name: string;
public render(): this {
this.name = 'name';
return this;
}
public test(): string {
return this.name;
}
}
const p = new Parent();
p.render().test();
索引类型
通过 keyof 将对象的key 作为 类型
interface IObject {
name: string,
age: number,
color: string
}
const obj = {
name: 'name',
age: 22,
color: 'red'
}
const key: keyof IObject = 'name'; // 相当于 'name' | 'age' | 'color'
映射类型
用于将一个已知类型的属性转换类型
interface IObject {
name: string,
age: number,
color: string
}
type IReadOnlyObject = {
readonly [K in keyof IObject]: boolean
}
const a: IReadOnlyObject = {
name: false,
age: true,
color: false
}
a.name = true; // 报错只读