如何在Typescript中表达功能约定?

时间:2019-05-31 07:05:49

标签: typescript

我有一个函数,当其参数为undefined时可以返回undefined,否则它总是返回从其参数派生的值。例如:

function triple(value?: number) : number | undefined {
  return value && value * 3;
}

现在,当我使用此功能时,我知道,当我提供参数时,它不会返回undefined

const x = 3;
const tripleValue : number = triple(x);

毫不奇怪,TypeScript给了我TS2322: Type 'number|undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.

有什么方法可以告诉TypeScript triple 从不定义参数时返回undefined吗?

我正在将TypeScript 3.4.5与strictNullChecks一起使用。

要复制,请参阅此TS playground。确保单击选项并选中strictNullChecks

1 个答案:

答案 0 :(得分:0)

我会自己回答,因为@jonrsharpe还没有。

解决方案(根据@jonrsharpe的评论)是使用overloads为该函数创建两个签名。 这样,您就可以针对同一函数实现使用两个或多个不同的签名。

为了表示该函数在其参数为数字时始终返回数字,而在其参数为undefined时可能返回undefined,我们需要两个不同的签名:

function triple(value : number) : number;
function triple(value?: number) : number | undefined {
    return value && value * 3;
}

这使我可以在没有TSC抱怨的情况下使用该功能:

const x = 3;
const tripleValue : number = triple(x);

请参见TS playground进行演示,请记住在选项下启用strictNullChecks