我有以下函数,它接受类型为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
附加到类型中。