[英]TypeScript ignoring internal function logic when infering return type?
Given the following type definition and function:给定以下类型定义和 function:
type SetResponseType = 'returnNumber' | 'returnString';
const argumentTypedFunction = (arg: SetResponseType) => {
if (arg === 'returnNumber') {
return 123;
}
return 'abc';
}
argumentTypedFunction('returnNumber'); // 123 | 'abc'
Why doesn't typescript knows that the return type could only be of type number when 'returnNumber' is used as argument?为什么 typescript 不知道当使用 'returnNumber' 作为参数时,返回类型只能是数字类型? What do I have to do to make typescript infer the correct type depending on the parameter value?
我需要做什么才能使 typescript 根据参数值推断出正确的类型?
You can define your function using a function overload signature and get the inferred return type that you expect.您可以使用function 重载签名定义您的 function 并获得您期望的推断返回类型。 Here's a code sample using the example data you showed in the question:
这是一个使用您在问题中显示的示例数据的代码示例:
/** This signature returns a number when the parameter is "returnNumber" */
function argumentTypedFunction (param: 'returnNumber'): number;
/** This signature returns a string when the parameter is "returnString" */
function argumentTypedFunction (param: 'returnString'): string;
/** This is the implementation signature. It describes a combination of all possibilities */
function argumentTypedFunction (param: 'returnNumber' | 'returnString'): number | string {
return param === 'returnNumber' ? 123 : 'abc';
}
const num = argumentTypedFunction('returnNumber');
//^? const num: number
const str = argumentTypedFunction('returnString');
//^? const str: string
argumentTypedFunction('somethingElse'); /* Expected error 👍
~~~~~~~~~~~~~~~
No overload matches this call...(2769) */
Inference is ok, but being explicit is much better: it defines expectations of the types related to your code very clearly — both for you and consumers of your code — and can help the compiler to better help you in some cases if you accidentally make mistakes in your function implementation.推理是可以的,但显式更好:它非常清楚地定义了与代码相关的类型的期望——对你和你的代码的消费者——并且可以帮助编译器在某些情况下更好地帮助你,如果你不小心犯了错误在您的 function 实施中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.