打字稿通用联盟

时间:2018-11-15 18:24:46

标签: typescript typescript-typings typescript-generics

所以我有通用对象数组,并且想遍历,但是打字稿不允许。这是一些示例代码。有关如何解决此问题的任何建议。

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。我似乎无法分享代码。

1 个答案:

答案 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
});

Playground link