Home > other >  Exclude cannot remove undefined on Typescript
Exclude cannot remove undefined on Typescript

Time:12-09

I'm trying to remove the undefined from one object type. What I did is:

type T = Exclude<{
    foo: number | undefined;
    flag?: boolean | undefined;
}, undefined>

But the T result is still

type T = {
    foo: number | undefined;
    flag?: boolean | undefined;
}

Why the Exclude is not working?

Sorry, I forgot mention I still want keep the optional type. I updated the object. Suppossing we have one property is optional and another one is not. So the result I want is

type T = {
    foo: number;
    flag?: boolean;
}

CodePudding user response:

Assuming

type A = {
    foo?: number | undefined;
    flag?: boolean | undefined;
};

A can't receive undefined, otherwise its definition would've been

type UndefinableA = {
    foo?: number | undefined;
    flag?: boolean | undefined;
} | undefined;

Therefore, both Exclude<A, undefined> and Exclude<UndefinableA, undefined> will return A, since Exclude<T, U> does not act on properties:

Exclude from T those types that are assignable to U


You can loop for all the keys and exclude undefined from each one:

type OmitUndefined<T> = {[K in keyof T]: Exclude<T[K], undefined>};

then

type T = OmitUndefined<A>;

will be the same as

type T = {
    foo: number;
    flag?: boolean | undefined;
}

Since flag is optional, you can't remove undefined from it.

  • Related