TypeScript中如何通过类型描述元组数组中元组元素之间的关系?

How to describe the relationship between elements of tuple in array of tuples via types in TypeScript?

我想通过TypeScript中的类型来描述元组数组中元组元素之间的关系。

这可能吗?

declare const str: string;
declare const num: number;
function acceptString(str: string) { }
function acceptNumber(num: number) { }

const arr /*: ??? */ = [
    [str, acceptString],
    [num, acceptNumber],
    [str, acceptNumber], // should be error
];

for (const pair of arr) {
    const [arg, func] = pair;
    func(arg); // should be no error
}

TypeScript Playground link

现实世界的例子:TypeScript Playground link

你基本上是在要求我一直在调用 correlated record types 的东西,目前在 TypeScript 中没有直接支持。即使在您可以说服编译器在创建此类记录时捕获错误的情况下,它也没有真正具备验证类型安全性的能力。

实现此类类型的一种方法是使用 existentially quantified generics which TypeScript does not currently support directly。如果是这样,您就可以将您的数组描述为:

type MyRecord<T> = [T, (arg: T)=>void];
type SomeMyRecord = <exists T> MyRecord<T>; // this is not valid syntax
type ArrayOfMyRecords = Array<SomeMyRecord>;

下一个最好的办法可能是允许 ArrayOfMyRecords 本身是一个通用类型,其中数组的每个元素都是强类型的,具有类似的 T 值,以及一个辅助函数来推断更强的类型:

type MyRecord<T> = [T, (arg: T) => void];

const asMyRecordArray = <A extends any[]>(
  a: { [I in keyof A]: MyRecord<A[I]> } | []
) => a as { [I in keyof A]: MyRecord<A[I]> };

这使用 infererence from mapped types and mapped tuples。让我们看看实际效果:

const arr = asMyRecordArray([
  [str, acceptString],
  [num, acceptNumber],
  [str, acceptNumber] // error
]);
// inferred type of arr:
// const arr:  [
//   [string, (arg: string) => void], 
//   [number, (arg: number) => void], 
//   [string, (arg: string) => void]
// ]

让我们解决这个问题:

const arr = asMyRecordArray([
  [str, acceptString],
  [num, acceptNumber],
  [str, acceptString] 
]);
// inferred type of arr:
// const arr:  [
//   [string, (arg: string) => void], 
//   [number, (arg: number) => void], 
//   [string, (arg: string) => void]
// ]

所以这足以定义 arr。但是现在看看当你迭代它时会发生什么:

// TS3.3+ behavior
for (const pair of arr) {
  const [arg, func] = pair; 
  func(arg); // still error!
}

这就是缺乏对相关记录的支持让您感到恼火的地方。在 TypeScript 3.3 中,添加了对调用 unions of function types 的支持,但该支持并未涉及此问题,即:编译器将 func 视为函数的 union这与 arg 的类型完全 不相关 。当你调用它时,编译器决定它只能安全​​地接受 string & number 类型的参数,而 arg 不是(也不是任何实际值,因为 string & number 折叠为 never).

所以如果你这样做,你会发现你需要一个 type assertion 来让编译器平静下来:

for (const pair of arr) {
    const [arg, func] = pair as MyRecord<string | number>;
    func(arg); // no error now
    func(12345); // no error here either, so not safe
}

有人可能会认为这是你能做的最好的,然后就把它留在那里。


现在,有一种方法可以在 TypeScript 中对存在类型进行编码,但它涉及到类似 Promise 的控制反转。不过,在我们走这条路之前,问问自己:当您不知道 T 时,您实际上 会用 MyRecord<T> 做什么 ?你能做的唯一合理的事情就是用它的第二个元素调用它的第一个元素。如果是这样,您可以提供一个更具体的方法,即 执行 而无需跟踪 T:

type MyRecord<T> = [T, (arg: T) => void];
type MyUsefulRecord<T> = MyRecord<T> & { callFuncWithArg(): void };

function makeUseful<T>(arg: MyRecord<T>): MyUsefulRecord<T> {
    return Object.assign(arg, { callFuncWithArg: () => arg[1](arg[0]) });
}

const asMyUsefulRecordArray = <A extends any[]>(
    a: { [I in keyof A]: MyUsefulRecord<A[I]> } | []
) => a as { [I in keyof A]: MyUsefulRecord<A[I]> };

const arr = asMyUsefulRecordArray([
    makeUseful([str, acceptString]),
    makeUseful([num, acceptNumber]),
    makeUseful([str, acceptString])
]);

for (const pair of arr) {
    pair.callFuncWithArg(); // okay!
}

您的 real-world 示例可以进行类似修改:

function creatify<T, U>(arg: [new () => T, new (x: T) => U]) {
    return Object.assign(arg, { create: () => new arg[1](new arg[0]()) });
}

const map = {
    [Type.Value1]: creatify([Store1, Form1]),
    [Type.Value2]: creatify([Store2, Form2])
};

function createForm(type: Type) {
    return map[type].create();
}

在 TypeScript 中模拟存在类型与上述类似,只是它允许您对 MyRecord<T> 做任何您不知道 T 也能做的事情。由于在大多数情况下这是一小部分操作,因此直接支持这些操作通常更容易。


好的,希望对您有所帮助。祝你好运!