如果将可选参数指定为特定值,则返回类型“从不" [英] Return type 'never' if an optional parameter is given to be a specific value
问题描述
我有一个函数,该函数带有一个可选的 boolean
参数,默认为 false
.当参数为 false
时,该函数返回 string
.当参数为 true
时,该函数应返回 never
.
I have a function that takes an optional boolean
argument that defaults to false
. When the argument is false
, the function returns a string
. When the argument is true
, the function should return type never
.
这是我尝试过的:
function example(arg: true): never;
function example(arg = false): string {
//...
}
这感觉像应该起作用:推断 arg
具有 boolean
类型,以及当未传递或以 false
传递时, example
返回 string
.当它作为 true
传递时,重载开始,并且 example
返回 never
.
This feels like it should work: arg
is inferred to have a boolean
type, and when it is not passed or passed as false
, example
returns string
. When it is passed as true
, the overload kicks in and example
returns never
.
但是,这根本不起作用.TypeScript为 arg
提供类型为 true
,并使其为必需,并使 example
始终永远返回>.
However, this doesn't work at all. TypeScript gives arg
the type true
and makes it required and makes example
always return never
.
我也尝试过这种疯狂,并且走近了:
I also tried this craziness, and got closer:
function example(arg: false): string;
function example(arg: true): never;
function example(arg: boolean): string | never;
function example(arg = false): string | never {
//...
}
但是,编译器仍然不认为 arg
是可选的.
However the compiler still doesn't consider arg
to be optional.
推荐答案
这似乎可行:
function example(arg: true): never;
function example(arg?: false): string;
function example(arg: boolean): string;
function example(arg: boolean = false): never | string {
if (!arg) {
return 'foo';
}
throw new Error();
}
const foo = example(true); // typeof foo is never
const bar = example(false); // typeof bar is string
const baz = example(); // typeof baz is string
这篇关于如果将可选参数指定为特定值,则返回类型“从不"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!