【发布时间】:2021-07-24 14:52:46
【问题描述】:
我有一个Datum<T> 类型,其中T 可能是number 或string。 Datums 被收集为对象中的数组。我有一个aggregateDatums 函数,它接受对象、带有Datums 数组的键名,并返回一个数据。
export interface Datum<T extends string | number> {
key: T;
count: number;
}
const aggregateDatums = <
TKey extends string | number,
T extends { [k in K]: Datum<TKey>[] },
K extends keyof T
>(data: T, key: K): Datum<TKey>[] => {
return [];
};
const data = {
numeric: [{key: 1, count: 1}, {key: 2, count: 2}],
text: [{key: 'a', count: 1}, {key: 'b', count: 2}],
};
const aggregated = {
numeric: aggregateDatums(data, 'numeric'), // should be type Datum<number>[], but is Datum<string | number>[]
text: aggregateDatums(data, 'text'), // should be type Datum<string>[], but is Datum<string | number>[]
};
因为我传递了一个对象和一个保存数组的键,而不是直接传递Datums 的数组,所以结果是输入Datum<string | number>[]。我的目标是与源数组中Datums 的类型相对应的类型,即Datum<string>[] 或Datum<number>[]。关于如何实现这一点的任何提示?
简化了示例以仅显示问题。但如果我过度设计了可以更简单的分型,请告诉我。
另外,如果有人能推荐有关 TypeScript 高级类型的资源,我将不胜感激。不幸的是,大多数资源都是关于 Partial<T> 等类型的,而我知道你可以用类型做高级魔法:-)
【问题讨论】:
标签: typescript types type-inference