我从来没有使用过打字稿,在一些简短的教程之前和之后,我开始转换一个应用程序。 大多数情况下它很顺利,但在某些情况下,我觉得 TS 不理解代码。这是我无法理解的最新情况:
interface APIresponse { someProp: number | null }
interface parsedAPIresponse { someProp: number }
let apiResponse: APIresponse = { someProp: null }
function parseAPIresponse(response: APIresponse): parsedAPIresponse {
response.someProp = 1
return response
}
。和 TS 抱怨不兼容的返回值,number|null 不能分配给数字,即使在为其赋值 1 之后也是如此。
我正在尝试做的是解析来自 API 的响应。API 返回 number|null,我对此无能为力,但我在我的应用程序中避免了 null,所以我尝试解析 API 响应并转换 null。
不知道如何编写并完全避免在应用程序的 API 层之后出现空值。
这有效(例如,请参阅TS操场(:
function parseAPIresponse(response: APIresponse): parsedAPIresponse {
let parsedResponse: parsedAPIresponse = {
someProp: response.someProp || 0,
};
return parsedResponse;
}
在此示例中,我们创建一个具有正确返回类型的新对象,并返回此对象,以便 TypeScript 了解它是预期的正确返回类型。
为了确保number
字段确实不是 null,我在这里选择使用默认值0
,当然可能还有其他一些方法(如果值不是数字,您可以抛出异常,或者使用另一个默认值,如NaN
等......