1

I would like to create an interface where values of one array attribute can be only a subset of values of another array attribute. So it would work like this:

interface Arrays {
    array: string[],
    subArray: ... // some type, string[] is not enough
}

const arrayOne: Arrays = {
    array: ['a', 'b', 'c'],
    subArray: ['a', 'b'], // ok, both 'a' and 'b' are in array
};

const arrayTwo: Arrays = {
    array: ['a', 'b', 'c'],
    subArray: ['a', 'd'], // incorrect type, 'd' is not in array
};

I can validate it at runtime, but is there a way to do it in typescript?

Václav Pruner
  • 310
  • 1
  • 11

1 Answers1

1

One way would be to extract the allowed values e.g.

type AllowedChars = ["a", "b", "c"]

interface Arrays<T> {
  array: T,
  subArray: Partial<T>
}

const arrayOne: Arrays<AllowedChars> = {
  array: ['a', 'b', 'c'],
  subArray: ['a', 'b'], // ok, both 'a' and 'b' are in array
};

const arrayTwo: Arrays<AllowedChars> = {
  array: ['a', 'b', 'c'],
  subArray: ['a', 'd'], // incorrect type, 'd' is not in array
};
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107