typescript 要求接口上字段是同一接口中数组的成员

q8l4jmvw  于 2023-01-03  发布在  TypeScript
关注(0)|答案(1)|浏览(154)

如何编写一个接口,其中一个字段是同一接口中数组类型的成员?
到目前为止,我得到了这个:

interface Example<F extends string = string> {
  fruits: ReadonlyArray<F>;
  defaultFruit: F;
}

// or equivalently:
interface Example<F extends ReadonlyArray<string> = ReadonlyArray<string>> {
  fruits: F;
  defaultFruit: F[number];
}

但问题是,这些将允许这样的事情:

const e: Example = {
  fruits: ["Apple", "Banana"],
  defaultFruit: "Something Else",
}

因为F将自身扩展到"Apple" | "Banana" | "Something Else"
我可以明确地这样做,比如

interface Example<F extends string> {
  fruits: ReadonlyArray<F>;
  defaultFruit: F;
}

const e: Example<"Apple" | "Banana"> = {
  fruits: ["Apple", "Banana"],
  defaultFruit: "Something Else", // <- correctly complains that this is not assignable to F
}

但是我不想把所有的东西都写两遍。我希望能够有:

const e: SomeInterface = {
  fruits: ["Apple", "Banana"],
  defaultFruit: "Something Else", // <- that disallows this.
}

有没有办法自动推导出来?谢谢。

lyfkaqu1

lyfkaqu11#

因为F会把自己扩展到"苹果"| "香蕉"| "其他东西"。
为了防止这种情况,您应该创建一个受F约束的单独生成。

工作示例

interface Example<F extends string, D extends F> {
  fruits: ReadonlyArray<F>;
  defaultFruit: D;
}

function check<F extends string, D extends F>(value: Example<F, D>){return value}

const e = check({
  fruits: ["Apple", "Banana"],
  defaultFruit: "Something Else", // Error Type '"Something Else"' is not assignable to type '"Apple" | "Banana"'
});

相关问题