获取 Typescript strictNullChecks 以使用未定义的返回香草 js 函数
Getting Typescript strictNullChecks to work with undefined returning vanilla js functions
使用惯用的 js returning undefined on error, converted to TS
function multiply(foo: number | undefined){
if (typeof foo !== "number"){
return;
};
return 5 * foo;
}
在新的 TS 代码中使用 multiply 时,我遇到编译器认为 doStuff 可以 return 未定义的问题,而实际上它不能。
所以我尝试编写一个由安全 TS 代码调用的此函数的 "unsafe" 版本,将安全版本留给常规 js 代码。
function unsafeMultiply(num: number){
return multiply(num);
}
由于 unsafeMultiply 只能接受一个数字,multiply 中的类型保护应该考虑 multiply 只会 return 一个数字,因为 unsafeMultiply 只能处理数字。
如果这对编译器来说太复杂了,我该如何强迫他接受我知道我在做什么?
When using multiply in new TS code i get the problem of the compiler believing doStuff can return undefined, when it cannot.
是的,它可以:multiply(undefined)
returns undefined
.
If this is too complicated for the compiler, how do i force him to accept i know what i'm doing ?
你可以做一个类型断言,因为你知道 multiply
只会 return undefined
如果用非数字调用它:
function unsafeMultiply(num: number) {
return multiply(num) as number;
}
或者您可以在运行时为类型保护添加代码:
function unsafeMultiply(num: number) {
let result = multiply(num);
if (typeof result === "undefined") {
throw new Error("Invalid num argument");
}
return result;
}
但如果是我,我会让 multiply
函数失败或 return NaN
而不是 returning undefined
,如果给定的话undefined
。那么就不需要unsafeMultiply
了。
使用惯用的 js returning undefined on error, converted to TS
function multiply(foo: number | undefined){
if (typeof foo !== "number"){
return;
};
return 5 * foo;
}
在新的 TS 代码中使用 multiply 时,我遇到编译器认为 doStuff 可以 return 未定义的问题,而实际上它不能。
所以我尝试编写一个由安全 TS 代码调用的此函数的 "unsafe" 版本,将安全版本留给常规 js 代码。
function unsafeMultiply(num: number){
return multiply(num);
}
由于 unsafeMultiply 只能接受一个数字,multiply 中的类型保护应该考虑 multiply 只会 return 一个数字,因为 unsafeMultiply 只能处理数字。 如果这对编译器来说太复杂了,我该如何强迫他接受我知道我在做什么?
When using multiply in new TS code i get the problem of the compiler believing doStuff can return undefined, when it cannot.
是的,它可以:multiply(undefined)
returns undefined
.
If this is too complicated for the compiler, how do i force him to accept i know what i'm doing ?
你可以做一个类型断言,因为你知道 multiply
只会 return undefined
如果用非数字调用它:
function unsafeMultiply(num: number) {
return multiply(num) as number;
}
或者您可以在运行时为类型保护添加代码:
function unsafeMultiply(num: number) {
let result = multiply(num);
if (typeof result === "undefined") {
throw new Error("Invalid num argument");
}
return result;
}
但如果是我,我会让 multiply
函数失败或 return NaN
而不是 returning undefined
,如果给定的话undefined
。那么就不需要unsafeMultiply
了。