![](/img/trans.png)
[英]Typescript return type based on argument with types not function overloading
[英]Typescript function return type based on argument
是否可以根据 TestType 的定义为showTest
TestType
设置动态返回类型?
如果参数是TestEnum.ONE
,那么返回类型将是boolean
,或者在这种情况下是TestEnum.TWO
,那么返回类型将是string
。
enum TestEnum {
ONE= 'one',
TWO= 'two'
}
type TestType = {
[TestEnum.ONE]: boolean;
[TestEnum.TWO]: number
}
const someObject = {
[TestEnum.ONE]: true,
[TestEnum.TWO]: 123
}
const showTest = (value: TestEnum) => {
const result = someObject[value];
if (typeof result === 'undefined') {
throw new Error(`Unable to find ${value} in object`);
}
return result;
};
showTest(TestEnum.ONE) // return true and return type is boolean
showTest(TestEnum.TWO) // return 123 and return type is number
您可以重载 function,因此它将接受TestEnum
并根据 value 的实际值返回不同的value
。
enum TestEnum {
ONE= 'one',
TWO= 'two'
}
function showTest(value: TestEnum.ONE): boolean;
function showTest(value: TestEnum.TWO): string;
function showTest(value: TestEnum): boolean | string {
if (value === TestEnum.ONE) return true;
else if (value === TestEnum.TWO) return "not one";
throw new Error('should never happen');
}
let shouldBeBoolean = showTest(TestEnum.ONE);
let shouldBeString = showTest(TestEnum.TWO);
找到了解决方案: 此处的 TS Playground 链接
enum TestEnum {
ONE= 'one',
TWO= 'two'
}
type TestType = {
[TestEnum.ONE]: boolean;
[TestEnum.TWO]: number
}
const someObject = {
[TestEnum.ONE]: true,
[TestEnum.TWO]: 123
}
const showTest = <K extends keyof TestType>(value: K): TestType[K] => {
const result = someObject[value];
if (typeof result === 'undefined') {
throw new Error(`Unable to find ${value} in object`);
}
return result;
};
const boolValue = showTest(TestEnum.ONE) // return true and return type is boolean
const numberValue = showTest(TestEnum.TWO) // return 123 and return type is number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.