【发布时间】:2020-12-07 18:21:55
【问题描述】:
鉴于此联合类型:
type Type = 'one' | 'two' | 'three'
我如何键入以下对象以确保它a) 涵盖Type 的所有可能值; b) 允许我拥有每种类型的函数签名?
const factories = {
one(a: string) { return /* whatever */ },
two(a: number, b: number) { return /* whatever */ },
three() { return /* whatever */ }
}
function getFactory<T extends keyof typeof factories>(type: T): typeof factories[T] {
return factories[type]
}
如果我没有像上面那样键入对象,我会进行完整的类型检查,但不是详尽无遗 - 我很容易忘记或拼错成员。在我的实际用例中,Type 有 30 多种可能性并且还在不断增长,所以这真的很重要。
如果我使用Record,例如const factories: Record<Type, any> 或const factories: Record<Type, Function>,它会详尽无遗,但我会放松对函数签名的类型检查。
【问题讨论】:
标签: typescript