Home > database >  View type intersection as object without | undefined for optional properties
View type intersection as object without | undefined for optional properties

Time:10-29

Example intersection:

interface ISelect {
    selectOnly?: boolean
}
interface IDefault {
    defaultValue: string
}

// intersection
type BothTypes = ISelect & IDefault

When I hover over BothTypes I'd like to see:

(alias) type BothTypes = {
    selectOnly?: boolean; // <------------ just boolean
    defaultValue: string;
}

What I've tried

With

type Resolve<T> = {
    [P in keyof T]: T[P]
}
type BothTypes = Resolve<ISelect & IDefault>

I get

(alias) type BothTypes = {
    selectOnly?: boolean | undefined; // <------------ | undefined added
    defaultValue: string;
}

I'd like to remove the | undefined. I tried the following but the Exclude doesn't work.

type Resolve<T> = {
    [P in keyof T]: Exclude<T[P], undefined>
}

Is this even possible?

Typescript Playground

CodePudding user response:

Typescript automatically adds undefined to an optional property.

If you want to prevent explicit undefined in an optional property try using --exactOptionalPropertyTypes or add "exactOptionalPropertyTypes": true to your tsconfig.json to change this behaviour.

For reference see Exact Optional Property Types .

With this option turned on the following works:

type Resolve<T> = {
    [P in keyof T]: T[P]
}

Updated Typescript Playground with exactOptionalPropertyTypes turned on.

  • Related