我有这个记录:
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 }
我希望我的函数只接受值为 typeA 的键
doStuff('b'); //this should fail
function doStuff(arg: keyof FilteredForTypeA): void {
...
}
这是我尝试过滤掉它们的方法
type FilteredForTypeA = { [k in keyof TheRecord]: TheRecord[k] extends TypeA ? TheRecord[k] : never }
最佳答案
这里发生了一些事情,所以我会回答,因为它不是我发现的相关现有问题的直接重复。
当您的类型具有索引签名时,如果它们是索引签名的子类型,则很难仅提取对象的“已知”文字键。即keyof {[k:string]:any,foo:any}
就是string
,"foo"
完全归入那。您可以使用条件类型技巧仅提取已知的文字键,如 this related question 所示。 :
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>;
另一方面,您只需要其值具有与特定类型匹配的属性的键。这可以通过映射条件查找来实现,如 this related question 所示。 :
type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
把它们放在一起,你会得到:
type KnownKeysMatching<T, V> = KeysMatching<Pick<T, KnownKeys<T>>, V>
并且您可以验证它是否按我认为的那样工作:
function doStuff(arg: KnownKeysMatching<TheRecord, TypeA>): void {
}
doStuff('a'); // okay
doStuff('b'); // error!
doStuff('c'); // okay
doStuff('d'); // error!
注意 arg
不能是 'b'
,但它也不能是 'd'
或任何其他“未知”字符串,即使 TheRecord
具有字符串索引签名。如果您需要 'd'
的其他行为,可以这样做,但这似乎超出了问题的范围。
希望有所帮助;祝你好运!
关于typescript - 如何根据值过滤记录键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979982/