I am working with a union type that has a discriminator property called "type". I then define a Record<> where the keys are the "type" property values.
How can I specify the second generic parameter of the Record (Record< , this param>) so that the values in the map/record are inferred based on the corresponding key?
interface Dog {
type: 'dog';
breed: string;
}
interface Vehicle {
type: 'vehicle';
max_speed: number;
};
type Thing = Dog | Vehicle;
const printMap: Record<Thing['type'], (thing: Thing) => string> = {
'dog': x => `Dog ${x.breed}`,
// ^^^^^ Property 'breed' does not exist on type 'Thing'. Property 'breed' does not exist on type 'Vehicle'.
// How do I make TypeScript infer `x` is a Dog because the key/property name is 'dog'?
'vehicle': x => `Vehicle max speed ${x.max_speed}`
// ^^^^^^^^^ Property 'max_speed' does not exist on type 'Thing'. Property 'max_speed' does not exist on type 'Dog'.
// How do I make TypeScript infer `x` is a Vehicle because the key/property name is 'vehicle'?
}