【发布时间】:2019-12-30 14:34:00
【问题描述】:
我有一个工厂,它应该根据提供的枚举键返回一个函数。 这是在 switch case 中完成的,并且那里的所有功能都有不同的有效负载。
我试图实现的目标是为该函数提供这样的类型,它将隐式验证有效负载的所有类型和工厂的返回类型。请参阅下面的示例:
// the list of keys that are used for creation
enum keys {
key1 = 1,
key2 = 2
}
// here are interfaces, that tie each key with payload, that should be provided.
// Actually, payload is way more complex (another interfaces) but let's keep it simple
interface Test1 {
key: keys.key1;
payload: string;
}
interface Test2 {
key: keys.key2;
payload: number;
}
// this is the type, that comes to the function below
type tests = Test1 | Test2;
interface ReturnTypeOfTest1 { returnedObject1: number; }
interface ReturnTypeOfTest2 { returnedObject2: string; }
// this is how I'm configuring what should be returned depending on the key
// the return type is set to "ResourceModel", which infers a key from a function payload
// and identifies what exactly it should return
interface ModelOfTest {
[keys.key1]: ReturnTypeOfTest1;
[keys.key2]: ReturnTypeOfTest2;
}
type ResourceModel<R extends keys> = ModelOfTest[R];
ResourceModel 类型是基于另一个stackoverflow 问题Typescript: Return type of function based on input value (enum) 创建的
使用上面的类型,我可以验证有效负载的类型,但放松返回类型的验证:
function getTest(t: tests): any{
switch (t.key) {
case keys.key1: {
const data = t.payload; // is string
return {returnedObject1: 123 };
} case keys.key2: {
const data = t.payload; // is number
return {returnedObject2: '123' };
}
}
}
getTest({key: keys.key1, payload: '1' }); // ReturnTypeOfTest1 | ReturnTypeOfTest2
或者获得一个正确的返回类型,但是在 switch case 中丢失一个验证:
function getTest<T extends tests>(t: T): ResourceModel<T['key']> {
switch (t.key) {
case keys.key1: {
const d = t.payload; // string | number
return {returnedObject1: 123}; // also an error here, because it wants me to return both ReturnTypeOfTest1 & ReturnTypeOfTest2
} case keys.key2: {
const d = t.payload; // string | number
return null;
}
}
}
getTest({key: keys.key2, payload: 1 }); // ReturnTypeOfTest2
有没有办法正确输入这个东西?非常感谢您对此提供任何帮助。
【问题讨论】:
-
让编译器推断返回类型。显式类型化为返回
any的函数在 99% 的情况下表明存在误解。
标签: typescript typescript-typings