mod7ex
mod7ex

Reputation: 948

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

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

Upvotes: -1

Views: 26

Answers (1)

nullptr
nullptr

Reputation: 4484

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'
}

Upvotes: 1

Related Questions