Reputation: 394
I am writing a Graph component, that has a config for x
and y
axis.
I want the GraphProps
to be used like so:
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
}
}
I have the following Typescript code:
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>;
}
however with the current definition the formatText
type is Stock[keyof Stock]
which equals Stock['timestamp' | 'value' | 'company']
, when what I want is, if the provided dataKey
is company
, i would like for the formatText
type to be Stock['company']
.
I thought of extending the GraphProps
generic type with 2 more type parameters(GraphProps<T, XDataKey, YDataKey>
), however I might add more than two axes and/or dynamically many more axes.
Upvotes: 1
Views: 118
Reputation: 51816
Define AxisType<T>
and GraphProps<T>
like this:
type AxisType<T> = {
[K in keyof T]: {
dataKey: K;
formatText: (point: T[K]) => string;
};
}[keyof T];
type GraphProps<T> = {
[axis: string]: AxisType<T>;
};
Upvotes: 1