Typescript required type based on value

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?


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


See also related docs