如何在打字稿中声明一组通用容器?

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

考虑我们的类型,

type Types = 'a' | 'b'

和我们的容器:

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

现在有两种方法可以声明这些容器的数组。我的问题是,我没有清除在不写出所有可能的容器类型的情况下编写第一个(好?)数组的方法。

我们将不胜感激您的帮助,或者任何关于一起完成这一切的更好方法的见解:)

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
    },
];

在这种情况下,您应该使用 distributivity 条件类型。

很容易实现。只需使用 type Helper<T> = T extends any ? ...

C考虑这个例子:

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