Typescript 中的实用程序类型 Partial、Required、ReadOnly、Record

303 阅读1分钟

1.Partial 将类型定义改为可选

interface Todo {
    name: string;
    age: number;
}
Partail<Todo>
// 等同于
interface Todo {
    name?: string;
    age?: number;
}

2.Required 将可选的类型定义改为必填

interface T {
    name?: string;
    age?: number;
}
Required<T>
// 等同于
interface T {
    name: string;
    age: number;
}

3.ReadOnly 构造一个 Type 的所有属性都设置为 readonly 的类型

interface Todo {
    title: string;
}
const todo: ReadOnly<Todo> {
    title: 'to do list'
}
todo.title = 'list';
// Cannot assign to 'title' because it is a read-only property.

4.Record Record<K,T> 的作用是将 K 中所有的属性的值转化为 T 类型

interface CatInfo {
    name: string;
    age: number;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
    miffy:{name:'mimi',age:10},
    boris:{name:'ok',age:9},
    mordred:{name:'xiaohua',age:8},
}