【发布时间】:2020-07-30 08:48:30
【问题描述】:
我正在编写一个图形组件,该组件具有x 和y 轴的配置。
我希望像这样使用GraphProps:
type Stock = {
timestamp: string;
value: number;
company: 'REDHAT' | 'APPLE' | ... ;
}
const props: GraphProps<Stock> = {
x: {
dataKey: 'timestamp',
// type-checks that timestamp is a string
formatText: timestamp => new Date(timestamp).toDateString()
},
y: {
dataKey: 'company',
// type-checks that company is 'APPLE' | 'REDHAT' | ...
formatText: company => company === 'APPLE' ? 'Apple' : company
}
}
我有以下打字稿代码:
type AxisType<T> = {
dataKey: keyof T;
// i want point to be:
// T[dataKey]
// how can I access dataKey from within the formatText
// type definition?
formatText: (point: T[keyof T]) => string;
}
type GraphProps<T> = {
x: AxisType<T>;
y: AxisType<T>;
}
但是,对于当前定义,formatText 类型是 Stock[keyof Stock],它等于 Stock['timestamp' | 'value' | 'company'],当我想要的是,如果提供的 dataKey 是 company,我希望 formatText 类型是Stock['company']。
我想用 2 个类型参数 (GraphProps<T, XDataKey, YDataKey>) 扩展 GraphProps 泛型类型,但是我可能会添加两个以上的轴和/或动态添加更多的轴。
【问题讨论】:
标签: javascript reactjs typescript typescript-generics