TypeScript在推断返回类型时忽略内部函数逻辑?

eanckbw9  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(151)

给定以下类型定义和函数:

type SetResponseType = 'returnNumber' | 'returnString';

const argumentTypedFunction = (arg: SetResponseType) => {
    if (arg === 'returnNumber') {
        return 123;
    }

    return 'abc';
}

argumentTypedFunction('returnNumber'); // 123 | 'abc'

当'returnNumber'被用作参数时,为什么typescript不知道返回类型只能是number类型?我必须做些什么才能让typescript根据参数值推断正确的类型?

bf1o4zei

bf1o4zei1#

您可以使用函数重载签名来定义函数,并获得所需的推断返回类型。以下代码示例使用了您在问题中显示的示例数据:
TSPlayground

/** 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) */

推理是可以的,但明确得多:它非常清楚地定义了与你的代码相关的类型的期望值--对你和你的代码的消费者都是如此--并且在某些情况下,如果你在你的函数实现中不小心犯了错误,它可以帮助编译器更好地帮助你。

相关问题