一、类型断言
1. 尖括号
let length = (<string>value).length;
2. as 语法
let length = (value as string).length;
3. 非空断言
x! 将从 x 值域中排除 null 和 undefined
4. 确定断言
let x!: number;
二、关键字
1. typeof
function myFun(value: string | number) {
if (typeof value === "number") {
...
}
if (typeof padding === "string"){
...
}
}
2. instanceof
3. in 判断属性是否存在对象中
if ('name' in person)
type Keys = "a" | "b" | "c"
type Obj = {
[p in Keys]: string
} // -> { a: string, b: string, c: string }
4. infer
在条件类型语句中,可以用 infer 声明一个类型变量并且对它进行使用
三、内置类型工具函数
1. Partial
通过泛型让目标类型中的所有属性变为可选属性生成一个新的类型
2. Omit
通过泛型删除指定属性生成新的类型
interface Person {
name: string;
age: number;
sex: "男" | "女";
}
type PersonOmit = Omit<Person, "age">;
const person1: PersonOmit = {
name: "小明",
sex: "男",
};
3. Pick
通过泛型选择指定的属性生成新的类型
interface User {
id: number;
age: number;
name: string;
}
// 相当于: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">;
// 相当于: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">;
4. Extends
Interface extends interface
type Dog = Animal & { color: string; };
5.NonNullable
NonNullable 用于从一个类型中排除 null 和 undefined。
6.ReturnType
获取函数类型T的返回值类型。它接受一个函数类型作为参数,并返回该函数的返回值类型。
function foo(): string {
return "Hello, world!";
}
type FooReturnType = ReturnType<typeof foo>; // string
class Person{
getName(){
return ""
}
}
// 以 Person 的方法返回的值 作为 类型;
let name: ReturnType<Person['getName']>;
7.InstanceType
InstanceType 用于获取构造函数的实例类型。InstanceType 接受一个构造函数类型作为参数,并返回该构造函数类型的实例类型。
8. Record<Keys, Type>
interface User {
name: string
age: number
}
type UserName = 'a' | 'b' | 'c'
const users: Record<UserName, User> = {
a: { name: 'ming', age: 23 },
b: { name: 'hong', age: 24 },
c: { name: 'huang', age: 25 }
}