是否可以在打字稿中键入“未排序的”元组?
type Test = UnsortedTuple<"Foo" | "Bar">;
const t1: Test = ["Foo", "Bar"]; // OK
const t2: Test = ["Bar", "Foo"]; // OK
const t3: Test = ["Bar"]; // Error: "Foo" is missing
const t3: Test = ["Foo", "Bar", "Bar"]; // Error: Extra "Bar"
const t5: Test = ["Baz", "Bar"]; // Error: "Baz" is not assignable to "Foo" | "Bar"
编辑:我使用了两个元素进行说明。但是,正在寻找一种适用于任何数量的元素类型的解决方案。
答案 0 :(得分:0)
错误消息在某些情况下并没有真正的帮助,但它们确实存在 对于mroe小于2的元组,这种方法虽然会变得很成问题
type UnsortedTuple<A, B> = [A, B] | [B, A];
type Test = UnsortedTuple<'Foo','Bar'>;
const t1: Test = ["Foo", "Bar"]; // OK
const t2: Test = ["Bar", "Foo"]; // OK
const t3: Test = ["Bar"]; // Error: Property '1' is missing in type '["Bar"]' but required in type '["Bar", "Foo"]'
const t3: Test = ["Foo", "Bar", "Bar"]; // Type '["Foo", "Bar", "Bar"]' is not assignable to type '["Foo", "Bar"]' Types of property 'length' are incompatible
const t5: Test = ["Baz", "Bar"]; // Error: Type '"Baz"' is not assignable to type '"Foo" | "Bar"'