How to do this type-safely: "the types 'Vehicle<C>' and 'Vehicle<CarConfig>' have no overlap"
The way to go would be a discriminated union :
type VehiculeType= 'Car' | 'Truck';
interface Vehicle<C> {
id: string
name: string
config: C | null
type: VehiculeType;
}
interface CarConfig {
leatherSeats: boolean
}
const Car: Vehicle<CarConfig> = {
type: 'Car',
id: "car",
name: "car",
config: null
}
interface TruckConfig {
numberOfWheels: number
}
const Truck: Vehicle<TruckConfig> = {
type: 'Truck',
id: "truck",
name: "truck",
config: null
}
function getVehicleConfig<C>(vehicle: Vehicle<C>): C | null {
if (vehicle.type === 'Car') {
return vehicle.config
}
if (vehicle.type === 'Truck') {
return vehicle.config
}
throw new Error("Unknown vehicle")
}