Closed
Description
It does not seem to be possible to change the discriminant from one property to another and have that recognised as the proper type.
TypeScript Version: 3.8.0-dev.20191116
Search Terms: discriminated union, discriminant, kind, type
Code
interface Car {
kind: 'car'
trunkSize: number
}
interface Bike {
kind: 'bike'
handlebarColor: string
}
interface ApiCar {
type: 'car'
trunkSize: number
}
interface ApiBike {
type: 'bike'
handlebarColor: string
}
type Vehicle = Car | Bike
type ApiVehicle = ApiCar | ApiBike
const unknown = {
type: 'car',
trunkSize: 5
}
function makeVehicle(vehicle: ApiVehicle): Vehicle {
return { ...vehicle, kind: vehicle.type }
}
Expected behavior:
Object returned by makeVehicle
should successfully be interepreted by the compiler as a Vehicle
Actual behavior:
Does not compile with the following error:
Type '{ kind: "car" | "bike"; type: "car"; trunkSize: number; } | { kind: "car" | "bike"; type: "bike"; handlebarColor: string; }' is not assignable to type 'Vehicle'.
Type '{ kind: "car" | "bike"; type: "car"; trunkSize: number; }' is not assignable to type 'Vehicle'.
Type '{ kind: "car" | "bike"; type: "car"; trunkSize: number; }' is not assignable to type 'Car'.
Types of property 'kind' are incompatible.
Type '"car" | "bike"' is not assignable to type '"car"'.
Type '"bike"' is not assignable to type '"car"'.(2322)