在 Typescript 中,我想根据函数的参数确定函数的返回类型。在下面的示例中,如果使用
getPropsForComponentKey
类型的参数调用 ComponentKey.A
,则其返回类型应为 AProps
。我应该能够使用控制流分析来防止返回具有不兼容类型的值。但是,我不确定如何描述此函数的类型,以便它期望在传入“A”时返回AProps
。
我尝试使用泛型类型
T
,并使用它来索引到索引访问类型 PropTypesForComponentKey
,以便返回类型将解析为 AProps
或 BProps
,具体取决于传递的内容进入功能。编译器错误表明 AProps
不可分配给 PropTypesForComponentKey[T]
.
type AProps = {
value: number;
}
type BProps = {
description: string;
}
enum ComponentKey {
A = 'A',
B = 'B',
}
type PropTypesForComponentKey = {
[ComponentKey.A]: AProps;
[ComponentKey.B]: BProps;
}
// this object enforces the mapping between key and value types
const propsForComponentKey: PropTypesForComponentKey = {
[ComponentKey.A]: { value: 3 },
[ComponentKey.B]: { description: 'foo' },
}
// we know that aProp is of type AProps when we use 'A' as an index into propsForComponentKey
const aProp = propsForComponentKey['A'];
// How do I enforce the return type of this function?
function getPropsForComponentKey<T extends ComponentKey>(componentKey: T): null | PropTypesForComponentKey[T] {
switch(componentKey) {
case ComponentKey.A:
return { value: 3 } as AProps;
case ComponentKey.B:
return { description: 'foo' };
}
return null;
}