Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript property only allowed if another property exists

Say I have a function in which I want to only allow a property if another property is present.

I tried to do it like this, but it returns with error Property 'c' does not exist on type 'A'.

type A = {
  a?: string;
} & ({ b: string; c?: string } | { b?: string });

const sad = (props: A) => {
  const { a, b } = props;

  const { c } = props;  // Property 'c' does not exist on type 'A'.

  return { a, b };
};

Any solutions to this?

like image 423
medzz123 Avatar asked Nov 06 '22 06:11

medzz123


1 Answers

The only way i know is User defined Type Guard and i like to combine it with Union Types

interface CommonProps {
    a?: string
    b?: string
}

interface SimpleProps extends CommonProps {
    kind: "simple"
}

interface ComplexProps extends CommonProps {
    kind: "complex"
    c?: string
}


type Props = SimpleProps | ComplexProps

function isComplex(arg: Props): arg is ComplexProps {
    return arg && arg.kind === 'complex'
}

const sad = (props: Props): any => {
    if (isComplex(props)) {
        const {a, b, c} = props
        // do something
        // return something
    }
    const { a, b } = props
    // do something
    // return something
}

In a nutshell, i create an interface for each possible combinations of properties. Then i Union them under the Props types, and in my function i use the user defined guards to access the properties.

like image 178
Anthony Raymond Avatar answered Nov 14 '22 22:11

Anthony Raymond