从类型中删除 undefined

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)

有没有办法摆脱undefinedFooOrUndefined

for*_*d04 29

你会想要使用NonNullable

type Foo = NonNullable<FooOrUndefined> // { bar: number; }
Run Code Online (Sandbox Code Playgroud)

样本

  • @Daniel 对于您想要“必需”的嵌套类型/接口(https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype) (2认同)

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)