我使用typeof
来推断函数的返回类型,但是由于我无法调用实际函数,因此我使用了一个使用三元运算符的技巧来推断该类型,但是这给我留下了包含undefined
的联合类型。 :
function foo() {
return { bar: 1 };
}
const fooInstance = true ? undefined : foo(); // foo() is never actually called
type FooOrUndefined = typeof fooInstance; // {bar: number} | undefined
type Foo = ???; // Should be { bar: number }
有没有办法从undefined
中摆脱FooOrUndefined
?
您将要使用NonNullable
:
NonNullable
[Sample,但我还发现,ford04 pointed me to NonNullable
是实现我要执行的操作的更简洁的方法: