Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove undefined from type

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?

like image 389
larsmoa Avatar asked Jan 16 '20 13:01

larsmoa


People also ask

How do I remove undefined in TypeScript?

Use the NonNullable utility type to remove null and undefined from a type in TypeScript. The NonNullable utility type constructs a new type with null and undefined excluded from the type.

How do you solve if an object is undefined?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

Is not null or undefined TypeScript?

To check for null or undefined , compare the value to both null and undefined , e.g. if (name === undefined || name === null) {} . If either of the two conditions is met, the variable stores a null or undefined value and the if block will run.


2 Answers

You will want to use NonNullable:

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

Sample

like image 58
ford04 Avatar answered Oct 02 '22 12:10

ford04


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
like image 37
Leon Avatar answered Oct 02 '22 13:10

Leon