42

I use typeof to infer the return type of a function, but since I cannot call the actual function I use a trick using the ternary operator to infer the type, however this leaves me with a union type that includes 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 }

Is there any way to get rid of undefined from FooOrUndefined?

4 Answers 4

66

You will want to use NonNullable:

type Foo = NonNullable<FooOrUndefined> // { bar: number; }

Sample

2
6

If you just want to remove undefined but keep null, you can do a small util:

type NoUndefined<T> = T extends undefined ? never : T;

type Foo = number | string | null | undefined;

type Foo2 = NoUndefined<Foo> // number | string | null
3

ford04 pointed me to NonNullable, but I also discovered that ReturnType is a cleaner way of achieving what I'm trying to do:

function foo() {
  return { bar: 1 };
}
type Foo = ReturnType<typeof foo>; // { bar: number; }
1

Use Exclude type of Utility Types of TypeScript:

function foo() {
  return { bar: 1 };
}

const fooInstance = true ? undefined : foo(); // foo() is never actually called
type FooOrUndefined = typeof fooInstance;     // {bar: number} | undefined 
type Foo = Exclude<FooOrUndefined, undefined>;// { bar: number }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.