TypeScript提供了几种实用类型来促进常见的类型转换。这些实用类型可在全局范围内使用。
Awaited
获取异步操作返回值的类型async function test() {
let aa:Promise<string> = new Promise((resolve) => resolve('namw'));
// 上面的相当于Promise.resolve('namw');
let myNames: Awaited<typeof aa> = await aa;
console.log(myNames) // 'namw'
// 实际上myNames为string类型,方便提取异步resolve返回值
}
test();
获取的是递归异步返回类型
type B = Awaited
type B = number
Partial
interface Person {
name: string;
age: string;
hobit?: string;
}
// 定义了一个人类接口,但是想命名一个继承它所有属性的未知变量,所有属性为可选,这样ts就不会报错了
const newPerson: Partial<Person> = {
name: '未定义的人类'
}
Required
interface Person {
name: string;
age: string;
hobit?: string;
}
const newPerson: Required<Person> = {
name: '未定义的人类'
}
// Type '{ name: string; }' is missing the following properties from type 'Required': age, hobit(2739)
Readonly
interface Person {
name: string;
age: string;
hobit?: string;
}
let newPerson: Readonly<Person> = {
name: '未定义的人类',
age: '14'
}
newPerson.age = '15'
// Cannot assign to 'age' because it is a read-only property.(2540)
// 下面无报错
interface Person {
name: string;
age: {
virtual:number;
truth:number;
};
hobit?: string;
}
const newPerson: Readonly<Person> = {
name: '未定义的人类',
age: {
virtual: 12,
truth: 13
}
}
newPerson.age.truth = 14;
Record
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
// cats上有CatName个属性,每个属性对应的值类型为CatInfo
cats.boris;
Pick
interface Todo {
title: string;
description: string;
completed: boolean;
}
// 从Todo上获取属性"title" | "completed"
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
Omit
interface Todo {
title: string;
description: string;
completed: boolean;
}
// 从Todo上移除属性"description"
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
Exclude
type T0 = Exclude<"a" | "b" | "c", "a">;
// type T0 = "b" | "c"
type Shape = { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
type T3 = Exclude<Shape, { kind: "circle" }>
/* type T3 = {
kind: "square";
x: number;
} | {
kind: "triangle";
x: number;
y: number;
} */
Extract
Type
中提取可分配给Union
的所有并集成员来构造类型,及取交集type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// type T0 = "a"
type Shape = { kind: "circle"; radius: number }
| { kind: "square"; x: number }
| { kind: "triangle"; x: number; y: number };
type T3 = Extract<Shape, { kind: "circle" }>
/* type T3 = {
kind: "circle";
radius: number;
} */
NonNullable
type T1 = NonNullable<string[] | null | undefined>;
// type T1 = string[]