typescript - 通用类型 K 是 M 的键,而 M[key] 是特定类型
问题描述
有没有办法定义一种类型:
K extends keyof Interface1 and interface1[K] is type of Interface2
谢谢
解决方案
如果我理解正确,您想从中选择Interface1
一个值为Interface2
.
可以这样实现:
type PropertyOfValue<T, V> = {
[K in keyof T]-?: T[K] extends V
? K
: never
}[keyof T];
type MyType = PropertyOfValue<Interface1, Interface2>;
用法:
interface Interface1 {
foo: string;
bar: Interface2;
}
interface Interface2 {
baz: string;
}
type MyType = PropertyOfValue<Interface1, Interface2>; // "bar"
推荐阅读
- html - index.html 和其他 html 文件应该放在哪里:根目录或 dist/build 文件夹?
- windows - Sleep() 睡眠时间过长
- mysql - 为 where 子句和 order_by 创建 MYSQL 索引
- python - Error_Running_Generate_Function_BART_module
- spring-boot - Spring Batch Composite Item Writer 事务管理
- python-3.x - 为什么在 ResampleImageFilter 执行期间 SimpleITK 会崩溃?
- python - 在列 Pandas 数据框中提取列表
- javascript - 下划线(_s)修改navigation.js 移动菜单切换按钮
- unity3d - 线渲染器和子弹的射击方向不同
- c# - EF Core 过滤器枚举存储为使用 LIKE 运算符的字符串