lar*_*moa 13 typescript typescript-generics typescript2.0
我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 }
Run Code Online (Sandbox Code Playgroud)
有没有办法摆脱undefined的FooOrUndefined?
for*_*d04 29
你会想要使用NonNullable:
type Foo = NonNullable<FooOrUndefined> // { bar: number; }
Run Code Online (Sandbox Code Playgroud)
Leo*_*eon 12
如果你只想删除undefined但保留null,你可以做一个小实用程序:
type NoUndefined<T> = T extends undefined ? never : T;
type Foo = number | string | null | undefined;
type Foo2 = NoUndefined<Foo> // number | string | null
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3190 次 |
| 最近记录: |