Search code examples
typescript

How to cast nullable type to non-nullable type (in typescript)?


I would like to cast nullable type into non-nullable type.

For example, if I have a type like:

const type A = {b: "xyz"} | null

then I would like to extract:

{b:"xyz"}

by doing like:

A!

but it doesnt work(of course, ! operator is for nulllable "variables", not nullable "types").

Could someone help me solve this problem? Thanks!


Solution

  • If you have a type:

    type A = {b: "xyz"} | null
    

    Using NonNullable will remove both null and undefined from your union type:

    type NonNullableA = NonNullable<A>
    

    If you want to only remove null but still keep undefined you can use Exclude:

    type NullExcludedA = Exclude<A, null>
    

    In this case both NonNullableA and NullExcludedA will yield the type you seek:

    {b:"xyz"}