从类型中删除未定义

问题描述 投票:0回答:2

我使用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

typescript typescript2.0 typescript-generics
2个回答
3
投票

您将要使用NonNullable

NonNullable

0
投票

[Sample,但我还发现,ford04 pointed me to NonNullable是实现我要执行的操作的更简洁的方法:

© www.soinside.com 2019 - 2024. All rights reserved.