typescript - 排除方法的打字稿键
问题描述
我想通过使用keyof
功能和排除方法never
,但它不起作用:
class A {
prop = 1;
save() {}
hello() {}
}
type ExcludeFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : T[K]
};
function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
return { } as any;
}
test(new A()).prop; // I still see here `save` and `hello`
我的理解是never
应该删除它们。
解决方案
这是一个解决方案来做你正在尝试的事情:
class A {
prop = 1;
save() {}
hello() {}
}
type ExcludeFunctionPropertyNames<T> = Pick<T, {
[K in keyof T]: T[K] extends Function ? never : K
}[keyof T]>;
function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
return { } as any;
}
test(new A()) // only prop available;
您在本文中有所有解释:https ://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c
推荐阅读
- javascript - 为什么 axios 将当前 URL 附加到 Laravel / React 中的 API 调用?
- java - 在 Java 中的 http 请求期间网络无法访问,但卷曲域有效
- css - 如何通过变量获得较少的地图值?
- javascript - Xpath:如果存在子元素,如何在 xpath 中选择父注释的值
- c# - 高级 Datagrid 视图以获取 filterevent args
- php - 如何制作多页表格
- c++ - 如何通过套接字传输 ESP32-Cam 拍摄的图像?
- c# - 验证是否有文件夹并打开您的 PDF 文件 C#
- python - 会话变量丢失,在 Django
- python - 如何从 Telegram 组中抓取 Telegram 用户?