可选的泛型参数类型缩小



我有以下函数,它接受类型为T(泛型(的可选参数。

function test<T>(foo?: T) {
return foo;
}
const result = test("bar");
// result is type "bar" | undefined
const result2 = test();
// result2 is type "unknown"

如何正确键入此函数,使编译器能够判断result变量的类型为"bar"而不是"bar" | undefined,此外result2变量的类型是undefined而不是unknown

我会用函数重载来实现这一点:

function test<T>(foo: T): T;
function test<T>(foo?: undefined): undefined;
function test<T>(foo?: T): T | undefined {
return foo;
}
const result = test("bar"); // result is of type "bar"
const result2 = test(); //result2 is of type undefined

游乐场链接

您可以使用重载签名来实现这一点:

function test(): undefined;
function test<T>(foo: T): T;
function test<T>(foo?: T) {
return foo;
}
const result = test("bar");
// result is type "bar"
const result2 = test();
// result2 is type undefined

游乐场链接

之所以是"bar" | undefined,是因为您将foo设置为可选参数。可选参数与JS中的undefined相同,因此使用foo?: T会自动将| undefined附加到类型中。

最新更新