Skip to content

Unable to specify 'if T is optional' in a conditional Type #23126

@Roaders

Description

@Roaders

TypeScript Version: 2.8.1

Search Terms:
condition types, unions, optional, undefined

Code

interface StringOption{
    type: "string";
}

interface NumberOption{
    type: "number";
}

interface ISampleObject {
    requiredParam: string,
    optionalParam?: number
}

type MappedOptions<T> = {
    readonly [P in keyof T]: T[P] extends undefined ? StringOption : NumberOption;
}

const mappedObject: MappedOptions<ISampleObject> = {
    requiredParam: {type: "number"},
    optionalParam: {type: "string"}
}

Expected behavior:

as optionalParam is optional you should be able to switch on that in conditional type so that when mapped optionalParam is of type StringOption and requiredParam is of type NumberOption.

Actual behavior:
both types are of type NumberOption as neither extend undefined. A syntax is needed to say that a type includes a type in a union I suppose and as far as I know this is not yet available.

Playground Link:
Playground link

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions