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
?
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.
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.
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.
You will want to use NonNullable
:
type Foo = NonNullable<FooOrUndefined> // { bar: number; }
Sample
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With