How do I declare an array of generic containers in typescript?

Viewed 95

Consider our types,

type Types = 'a' | 'b'

and our container:

interface Container<T extends Types> {
    p: T,
    q: T,
}

Now here are two ways of declaring an array of these containers. My issue is that I have not clean a method of writing the first (good?) array without writing out all possible container types.

Some help would be greatly appreciated, or any insights into a better way of doing this all together :)

const goodArr: (Container<'a'> | Container<'b'>)[] = [
    {
        p: 'a',
        q: 'a',
    },
    {
        p: 'b',
        q: 'a', // compiler doesn't allow this
    },
];

const badArr: Container<Types>[] = [
    {
        p: 'a',
        q: 'a',
    },
    {
        p: 'b',
        q: 'a', // compiler allows this
    },
];
1 Answers

In this case you should use distributivity of conditional types.

It is easy to achieve. Just use type Helper<T> = T extends any ? ...

COnsider this example:

type Types = 'a' | 'b'


interface Container<T extends Types> {
  p: T,
  q: T,
}

type Allowed<T extends Types> = T extends string ? Container<T> : never

const goodArr: Allowed<Types>[] = [
  {
    p: 'a',
    q: 'a',
  },
  {
    p: 'b',
    q: 'a', // compiler doesn't allow this
  },
];

Playground

Related