Home > Software engineering >  How can i restrict the type of a field in an interface so that it only depends on other fields?
How can i restrict the type of a field in an interface so that it only depends on other fields?

Time:09-05

I have an interface

interface T {
    name: string[];
    pick: T['name'][number]
}

and for example if i choose name to be ['a', 'b'], pick can only be a or b

how can i do this ?

thanks in advance

CodePudding user response:

You can do it with generics like so:

interface MyType<T extends string> {
    name: T[];
    pick: T[number]
}


const v1: MyType<'abc' | 'bcd'> = {
  name: ['abc', 'bcd'],
  pick: 'a'
}

  • Related