![](/img/trans.png)
[英]Typescript function return type based on optional parameter presence without using function overloads
[英]How to change the return type of a function based on an optional parameter being provided?
我需要创建一个 function,如果提供了可选值,它会返回number
,而number | null
number | null
如果没有。
到目前为止,我已经尝试过:
type GetValueFn = {
(values: { defaultValue: number }): number | null;
(values: { defaultValue: undefined }): number;
}
const getValue: GetValueFn = ({ defaultValue }) => {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (defaultValue !== undefined) return defaultValue;
return null;
}
但我收到一条错误消息:
类型“null”不可分配给类型“number”
这样做的正确方法是什么?
你只能使用一个定义。
?
=未定义
type GetValueFn = (values: { defaultValue?: number }): number | null;
const getValue: GetValueFn = ({ defaultValue }) => {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (!defaultValue) return defaultValue;
return null;
}
显然,typescript 中的 function 重载对于箭头函数仍然不能正常工作。 更多在这里。 我不知道这是否仍然准确。 如果您可以选择,您可以声明 function 之类的,它会正常工作。
interface Values {
defaultValue: number;
}
function getValue(values: Values) : number;
function getValue(values: Partial<Values>) : number | null;
function getValue(values: Values | Partial<Values>) {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (values.defaultValue !== undefined) return values.defaultValue;
return null;
}
在TS 游乐场工作
编辑: 更新演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.