typescript - 从对象类型中排除函数类型
问题描述
在以下代码摘录中:
interface User {
name: string;
age: number;
bestFriend: User;
getInfo: () => any;
}
type MyCustomType = {
[key in keyof User]: User[key]
};
有没有办法只删除该接口的函数类型?我已经创建了MyCustomType
类型,但是我没有找到删除函数类型的方法,例如getInfo
.
我怎样才能只允许该类型中的非函数类型MyCustomType
?
PS:User
不应该过滤掉的类型。
解决方案
这是 Typescript 手册的“高级类型”页面上列出的分布式条件类型示例之一。
条件类型在与映射类型结合使用时特别有用:
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 repo发现此类型当前不是内置实用程序类型(与未记录的类型Parameters<T>
和ConstructorParameters<T>
不同),因此您必须NonFunctionProperties
自己定义等价物。
推荐阅读
- spring-boot - 春天启动应用程序。失败“原因:java.lang.NoClassDefFoundError:org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata”
- node.js - 使用 Papaparse 将 JSON 转换为 CSV
- google-apps-script - Gmail 应用程序脚本:回复时执行功能
- node.js - Typeorm:查询以检查多对多关系中是否存在所有值?
- java - 使用 Java 查找按字母顺序排列的第一个字符串
- reactjs - 导航中如何根据 HOC 函数让 react 组件读取或编辑?
- javascript - 如何在 Discord.JS 中通过 ID 踢出 GuildMember?
- python - django.template.loaders.app_directories.Loader 不会在 installed_apps 中搜索模板
- assembly - 在原生 RISC-V 上构建我的汇编程序
- c - bash 直接执行溢出的字符