【发布时间】:2022-01-21 16:19:08
【问题描述】:
我对 TypeScript 中更高级的泛型类型有疑问。
我想要做的是一个数据数组,其中data 本身由type 控制,例如:
[
{
type: "T1",
content: number,
},
{
type: "T2",
values: {
id: number,
...
}
}
]
在描述了可用的类型后,我有点被堆积如山:
enum DataType {
T1 = "t1",
T2 = "t2"
}
所以我猜结果一定是这样的:
interface DataGeneric<T> {
[T extends DataType.T1]: { content: number },
[T extends DataType.T2]: { values: { id: number, ... } },
} ???
interface Data<T extends DataType = any(?)> extends DataGeneric<T>{
type: DataType,
// and all the other fields are generic from T = DataType
}
const someData: Data[] | undefined = fetchData();
// suggesting that the `type` of element[1] is "t2"
// and VSCode suggestions works correctly too,
// consider that there is an object-field `values` with `id` key
someData[1].values.id
提前致谢!
【问题讨论】:
-
您是否考虑过区分联合而不是泛型?见typescriptlang.org/docs/handbook/…
-
看起来你肯定想要一个有区别的联合而不是通用的,比如this。如果该代码满足您的需求,我可能会写一个答案。如果没有,请告诉我缺少什么。
-
@jcalz 是的,是的!非常感谢!
标签: typescript generics