If I define it in this way, it works
function process1() {
const yAxisType = 'primary';
const otherYAxisType = 'secondary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
function process2() {
const yAxisType = 'secondary';
const otherYAxisType = 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
I want to merge these two functions. But I kept getting TS errors. How can I resolve it? Thanks!
function process(yAxisType: 'primary' | 'secondary') {
const otherYAxisType = yAxisType === 'primary' ? 'secondary' : 'primary';
return {
[yAxisType]: foo,
[otherYAxisType]: bar
}
}
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is not assignable to type 'ComboChartSingleAxisEncoding'.
Type '{ [x: string]: { fields: never[]; } | { type: "quantitative"; }; scale: { type: "quantitative"; }; }' is missing the following properties from type '{ primary: ComboChartSingleAxisSectionEncoding; secondary: ComboChartSingleAxisSectionEncoding; scale: QuantitativeScale; }': primary, secondaryts(2322)
index.ts(85, 3): The expected type comes from property 'y' which is declared here on type 'ComboChartEncodingMap'
See Minimal repro on TS playground 👈
export type ComboChartAxisEncoding = ComboChartSingleAxisEncoding | ComboChartDualAxisEncoding;
export type ComboChartSingleAxisEncoding = {
primary: ComboChartSingleAxisSectionEncoding;
secondary: ComboChartSingleAxisSectionEncoding;
scale: 'quantitative';
};
export type ComboChartSingleAxisSectionEncoding = {
fields: number[];
};
export type ComboChartDualAxisEncoding = {
primary: ComboChartDualAxisSectionEncoding;
secondary: ComboChartDualAxisSectionEncoding;
};
export type ComboChartDualAxisSectionEncoding = {
fields: number[];
scale: 'quantitative';
};
function process1(): ComboChartAxisEncoding {
const yAxisType: 'primary' | 'secondary' = 'primary';
const otherYAxisType: 'primary' | 'secondary' = 'secondary';
return { // this works
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}
function process2(yAxisType: T): ComboChartAxisEncoding {
const otherYAxisType = (yAxisType === 'primary' ? 'secondary' : 'secondary') as (T extends 'primary' ? 'secondary' : 'primary');
// this doesn't work. Note that in my case this function wraps lots of test cases and each of them has this structure.
// So, if I don't have to change the structure of the JS objects, and just need to change the types, it would be better.
return {
[yAxisType]: { fields: [] },
[otherYAxisType]: { fields: [] },
scale: 'quantitative',
};
}