typescript - 值扩展 V 的键
问题描述
例如:
interface Foo {
a: string
b: string
c: number
}
我如何定义KeysOf<T, V>
这样的KeysOf<Foo, string>
give"a" | "b"
和KeysOf<Foo, number>
give "c"
?
我试过了type KeysOf<T, V> = T[infer K] extends V ? K : never
,但是 TypeScript 不允许infer
在extends
.
解决方案
您可以使用映射类型和条件类型来执行此操作:
interface Foo {
a: string
b: string
c: number
}
type KeyOf<T, V> = {
[P in keyof T]: T[P] extends V ? P : never
}[keyof T]
type S = KeyOf<Foo, string> //"a" | "b"
type N = KeyOf<Foo, number> //"c"
推荐阅读
- sql - SQL Server 仅选择字符串的一部分
- python - 这个 for 循环的时间复杂度是多少?
- javascript - 如何为每个唯一用户而不是 localStorage 实现持久化?
- r - 将一个向量与另一个向量的每个元素进行比较
- python - AttributeError:“NoneType”对象在覆盆子的速度监视器中没有属性“组”
- swiftui - 如何在 SwiftUI 中将 Closure 定义为 Button 的操作?
- python - 我对我的 python 代码的一部分感到困惑
- bash - TMUX - 分离时窗格大小调整不起作用?
- influxdb - 测量系列的持续时间 - InfluxDB 1.8
- node.js - 如何为 nodejs 运行启动命令,在 Azure 上表达 js 项目?