如何根据值过滤记录键?

Bir*_*sky 1 generics types generic-programming typescript typescript-generics

我有这个记录:

interface TheRecord extends TheRecordType {
  a: { typeA: 'string' },
  b: { typeB: 123 },
  c: { typeA: 'string' },
}

type TheRecordType = Record<string, TypeA | TypeB>

type TypeA = { typeA: string }
type TypeB = { typeB: number }
Run Code Online (Sandbox Code Playgroud)

我希望我的函数只接受值为 typeA 的键

doStuff('b'); //this should fail

function doStuff(arg: keyof FilteredForTypeA): void {
  ...
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过滤掉它们的方法

type FilteredForTypeA = { [k in keyof TheRecord]: TheRecord[k] extends TypeA ? TheRecord[k] : never }
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 5

这里发生了一些事情,所以我会做出回答,因为它不是我发现的相关现有问题的直接重复。

当您的类型具有索引签名时,如果它们是索引签名的子类型,则很难仅提取对象的“已知”字面键。也就是说,keyof {[k: string]: any, foo: any}is just string,并且"foo"完全包含在其中。您可以使用条件类型技巧来仅提取已知的文字键,如以下相关问题所示:

type KnownKeys<T> = Extract<{
    [K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never, keyof T>;
Run Code Online (Sandbox Code Playgroud)

另一方面,您只需要其值具有与特定类型匹配的属性的键。这可以通过映射条件查找来实现,如以下相关问题所示:

type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
Run Code Online (Sandbox Code Playgroud)

把它们放在一起,你会得到:

type KnownKeysMatching<T, V> = KeysMatching<Pick<T, KnownKeys<T>>, V>
Run Code Online (Sandbox Code Playgroud)

您可以验证它是否按我认为的那样工作:

function doStuff(arg: KnownKeysMatching<TheRecord, TypeA>): void {
}

doStuff('a'); // okay
doStuff('b'); // error!
doStuff('c'); // okay
doStuff('d'); // error! 
Run Code Online (Sandbox Code Playgroud)

请注意如何arg不能是'b',根据需要,但它也不能是'd'或任何其他“未知”字符串,即使TheRecord具有字符串索引签名。如果你需要一些其他的行为'd',那可以做到,但这似乎超出了问题的范围。

希望有所帮助;祝你好运!

代码链接