如果我有此界面:
interface Interface {
a: number
b: number
c: string
d: string
e: number[]
}
在Interface
中值的类型为/扩展特定类型的情况下,如何获取Interface
的键?就像Pick<T, K>
,但不是返回与类型匹配的键,而是返回其值与类型匹配的键。
我正在寻找这样的东西:
type KeyOfWhereValueMatches<T, U extends U[keyof U]> = // ???
KeyOfWhereValueMatches<Interface, number> // 'a' | 'b'
KeyOfWhereValueMatches<Interface, string> // 'c' | 'd'
KeyOfWhereValueMatches<Interface, number[]> // 'e'
答案 0 :(得分:2)
应该执行以下操作:
type KeyOfWhereValueMatches<
T,
U,
S = { [key in keyof T]: U extends T[key] ? key : never; }
> = S[keyof S]
工作原理:
T
是您的界面,U
是您要为其获取密钥的类型。
S
是通过接口类型的每个键运行的一种计算类型。如果U可分配给该键的类型(即number extends Interface[b]
),则该字段的新类型是其键的字符串文字。如果没有,那就永远不会。
对于KeyOfWhereValueMatches<Interface, number>
,S
等于:
interface S {
a: "a";
b: "b";
c: never;
d: never;
e: never;
}
最后,S[keyof S]
使用lookup types返回S
中所有可用键的类型。这些将是适当键的字符串文字,或者是never
。由于never
不会发生,因此查找仅返回字符串文字。