Open
Description
Search Terms
union to intersection, type merge
Suggestion
I'd like to either standardize (meaning documented behavior) or have a less hacky (future proof) way of transforming union types to intersections.
Use Cases
The most common use case I can think of is a basic action system where each action has some kind of input data it can work with to determine its disabled status. An actionGroup which packs multiple actions into one updater function needs to request the right input data type which is compatible to all of its actions.
While it's possible in the current version of typescript, it feels like a hack.
Examples
A more presentable form by describing a car dashboard:
interface Gauge<T> {
display(data: T): void;
}
class SpeedGauge implements Gauge<{ speed: number; }> {
display(data: { speed: number; }) {
}
}
class TempGauge implements Gauge<{ temperature: number; }> {
display(data: { temperature: number; }) {
}
}
class RevGauge implements Gauge<{ rev: number; }> {
display(data: { rev: number; }) {
}
}
type ExtractGaugeType<T> = T extends Gauge<infer U> ? U : never;
// evil magic by jcalz https://stackoverflow.com/a/50375286
// I would like to future proof or have a better version of this
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
class Dashboard<T extends Gauge<unknown>> {
constructor(public gauges: T[]) {
}
display(data: UnionToIntersection<ExtractGaugeType<T>>) {
this.gauges.forEach((g) => g.display(data));
}
}
const myDashboard = new Dashboard([new SpeedGauge(), new TempGauge(), new RevGauge()]);
/*
the type is: { rev: number; } & { speed: number; } & { temperature: number; }
*/
myDashboard.display({ // Ok
speed: 50,
rev: 2000,
temperature: 85
});
myDashboard.display({ // Error: property "rev" is missing
speed: 50,
temperature: 85
});
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.