Pick
type 包含在 TypeScript 中。它的实现如下:
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
你会怎么写
PickByValue
键入以便以下工作:type Test = {
includeMe: 'a' as 'a',
andMe: 'a' as 'a',
butNotMe: 'b' as 'b',
orMe: 'b' as 'b'
};
type IncludedKeys = keyof PickByValue<Test, 'a'>;
// IncludedKeys = 'includeMe' | 'andMe'
最佳答案
假设您打算 Test
是这样的:
type Test = {
includeMe: 'a',
andMe: 'a',
butNotMe: 'b',
orMe: 'b'
};
并假设您想要 PickByValue<T, V>
给出所有属于 V
的子类型的属性(这样 PickByValue<T, unknown>
应该是 T
),那么你可以定义 PickByValue
像这样:type PickByValue<T, V> = Pick<T, { [K in keyof T]: T[K] extends V ? K : never }[keyof T]>
type TestA = PickByValue<Test, 'a'>; // {includeMe: "a"; andMe: "a"}
type IncludedKeys = keyof PickByValue<Test, 'a'>; // "includeMe" | "andMe"
但如果您只想要 IncludedKeys
,然后您可以更直接地使用 KeysMatching<T, V>
执行此操作:type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];
type IncludedKeysDirect = KeysMatching<Test, 'a'> // "includeMe" | "andMe"
Playground link to code
关于typescript - 如何编写 PickByValue 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150760/