Home > Software engineering >  One property type is depent on other property value
One property type is depent on other property value

Time:11-11

type resp = {valid: boolean, prop1?: string, prop2?: string}

in the above scenario. prop1 and prop2 are in type string or undefined.

I want to design like. if the valid value is true that means prop1 and prop2 will be strings that won't have an undefined value.

How can I create a type for this task?

CodePudding user response:

Somehow I answered your question but in another question... If it's still relevant, here's the answer:

You could create a union type:

type Resp = ({valid: boolean, prop1: string, prop2: string} & { valid: true }) | 
   ({valid: boolean, prop1?: string, prop2?: string} & { valid: false });

const o1: Resp = {
    valid: true,
    prop1: 'a',
    prop2: 'b'
}

const o2: Resp = {
    valid: false,
}

Typescript playground

  • Related