在以下代码摘录中:
interface User {
name: string;
age: number;
bestFriend: User;
getInfo: () => any;
}
type MyCustomType = {
[key in keyof User]: User[key]
};
Run Code Online (Sandbox Code Playgroud)
有没有办法只删除该接口的函数类型?我已经创建了MyCustomType类型,但我没有找到删除函数类型的方法,例如getInfo.
如何只允许该MyCustomType类型中的非函数类型?
PS:User不应过滤掉诸如此类的类型。
这是 Typescript 手册的“高级类型”页面上列出的分布式条件类型示例之一。
条件类型与映射类型结合使用时特别有用:
Run Code Online (Sandbox Code Playgroud)type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>; type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]; type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>; interface Part { id: number; name: string; subparts: Part[]; updatePart(newName: string): void; } type T40 = FunctionPropertyNames<Part>; // "updatePart" type T41 = NonFunctionPropertyNames<Part>; // "id" | "name" | "subparts" type T42 = FunctionProperties<Part>; // { updatePart(newName: string): void } type T43 = NonFunctionProperties<Part>; // { id: number, name: string, subparts: Part[] }
快速搜索 Typescript Github 存储库会发现此类型当前不是内置实用程序类型(与未记录的类型Parameters<T>和 不同ConstructorParameters<T>),因此您必须NonFunctionProperties自己定义等效项。
这是杰夫综合答案的简化版本和 游乐场链接。
interface User {
name: string;
age: number;
bestFriend: User;
getInfo: () => any
}
// Do not worry too much about understanding this
// until you're ready for advanced TypeScript.
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? K : never
}[keyof T];
type MyCustomType = Omit<User, FunctionPropertyNames<User>>;
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
859 次 |
| 最近记录: |