Home > Enterprise >  Typescript required type based on value
Typescript required type based on value

Time:10-27

I am new to typescript and I was wondering if there is a way to make a type required based on the value of another type:

type TextInput = {
    isValid?: boolean;
    validMessage?: string;
}

Is it possible to make validMessage required if isValid becomes true?

CodePudding user response:

You need to use discriminated unions:

type Valid = {
    isValid: true;
    validMessage: string
}

type Invalid = {
    isValid: false;
}

type TextInput = Valid | Invalid


const foo = (props: TextInput) => {
    if (props.isValid) {
        props.validMessage // ok
    } else {
        props.isValid // false
        props.validMessage // error
    }
}

Playground

See also related docs

  • Related