所以我有通用对象数组,并且想遍历,但是打字稿不允许。这是一些示例代码。有关如何解决此问题的任何建议。
type someGeneric<T> = { item: T };
type stringGeneric = someGeneric<string>;
type numberGeneric = someGeneric<number>;
type someFunction = <T>(generic: someGeneric<T>) => T;
const someFunction: someFunction = (generic) => generic.item;
const stringGeneric: stringGeneric = { item: 'some String' },
numberGeneric: numberGeneric = { item: 12 };
let genericArray = [stringGeneric, numberGeneric];
genericArray.forEach(generic => {
someFunction(generic); // Error On This line.
});
您只需将代码复制粘贴到this link。我似乎无法分享代码。
答案 0 :(得分:2)
问题在于,如果我们尝试传入类型为someGeneric<T>
的参数,该函数将接受类型为someGeneric<number> | someGeneric<string>
的参数,打字稿将不会尝试由此推断T
说联合与类型someGeneric<T>
我们可以更改函数的定义,以便类型参数扩展someGeneric<any>
。此约束将与联合兼容。然后,我们可以使用条件类型使用条件类型从T
中提取项目类型。由于条件类型分布在并集上,因此提取的结果将是通用参数与someGeneric<T>
type someGeneric<T> = { item: T };
type stringGeneric = someGeneric<string>;
type numberGeneric = someGeneric<number>;
type extractItemFromSomeGeneric<T extends someGeneric<any>> = T extends someGeneric<infer U> ? U : never;
type someFunction = <T extends someGeneric<any>>(generic: T) => extractItemFromSomeGeneric<T>;
const someFunction: someFunction = (generic) => generic.item;
const stringGeneric: stringGeneric = { item: 'some String' },
numberGeneric: numberGeneric = { item: 12 };
let someGeneric = [stringGeneric, numberGeneric];
someGeneric.forEach(generic => {
someFunction(generic); // retruns string | number
});