Issue
As I filtered vehicles based on isCar so Ts should infer it as an array of Cars but TS infer it as Foo[]. How can I have a conditional type based on isCar??
interface Vehicle {
driveName: string
}
interface Bicycle extends Vehicle {
isCar: false,
saddleColor: string
}
interface Car extends Vehicle {
isCar: true
plate: string
}
type Foo = Bicycle | Car
const vehicles: Foo[] = [
{
driveName: "foo",
isCar: true,
plate: "1111"
},
{
driveName: "bar",
isCar: false,
saddleColor: "red"
}
]
const c = vehicles.filter(({ isCar }) => isCar) // typeof c is not Car
I found these questions but was not able to find an answer to my problem
Typescript Interface - Possible to make "one or the other" properties required?
Typescript asserting types if they have one property true or false
Solution
You need to use custom typeguard:
interface Vehicle {
driveName: string
}
interface Bicycle extends Vehicle {
isCar: false,
saddleColor: string
}
interface Car extends Vehicle {
isCar: true
plate: string
}
type Foo = Bicycle | Car
const vehicles: Foo[] = [
{
driveName: "foo",
isCar: true,
plate: "1111"
},
{
driveName: "bar",
isCar: false,
saddleColor: "red"
}
]
const isCar = (vehicle: Foo): vehicle is Car => vehicle.isCar
const c = vehicles.filter(isCar) // typeof c is not Car
Answered By - captain-yossarian from Ukraine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.