<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/12d678.md for this page in Markdown format</div>
enum MyEnum { A, B, C };如果我想要另一种类型,即该枚举的键的联合字符串,我可以执行以下操作:
typescript
type MyEnumKeysAsStrings = keyof typeof MyEnum; // "A" | "B" | "C"typescript
type Person = { age: number; name: string; alive: boolean };
type I2 = Person[keyof Person];
//type I2 = string | number | booleantypescript
const RestfulMethod = {
get: 'GET',
post: 'POST',
put: 'PUT',
delete: 'DELETE'
} as const
type IRestfulMethod = typeof RestfulMethod
type TypeRestfulMethod = IRestfulMethod[keyof IRestfulMethod]
// type TypeRestfulMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'typescript
type Person = { age: number; name: string; alive: boolean };
type I2 = keyof Person
//type I2 = 'age' | 'name' | 'alive'typescript
let obj = {
name: 'hello',
age: 18,
eat () {
return 'food'
},
link () {
return 'dog'
}
}
type methodsPick<T> = {[K in keyof T]: T[K] extends Function ? K : never}[keyof T];
// T1 = 'eat' | 'link'
type T1 = methodsPick<typeof obj>Partial<Type>
pick
通过从 Type 中选择一组属性 Keys(字符串文字或字符串文字的联合)来构造一个类型。
typescript
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
const todo: TodoPreviewomit
与pick相反,通过从 Type 中选择所有属性然后删除 Keys(字符串文字或字符串文字的联合)来构造一个类型。
typescript
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};