【发布时间】:2020-03-17 16:25:16
【问题描述】:
我有这个记录:
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 }
【问题讨论】:
-
呃,除非你有那个索引签名。您可能需要先使用
KnownKeys,如this question -
感谢@jcalz!让我消化..
标签: typescript generics types generic-programming typescript-generics