want to create an interface with conditional types based on a sub-property, like the one in the below example (here the Typescript playground), but into my test function I receive these two errors:
Property 'foo' does not exist on type 'BmwMetadata | AudiMetadata'. Property 'foo' does not exist on type 'AudiMetadata'.
Property 'bar' does not exist on type 'BmwMetadata | AudiMetadata'. Property 'bar' does not exist on type 'BmwMetadata'.
Could someone help me?
type BrandName = 'bmw' | 'audi' | 'ford'
interface Brand<T = BrandName> {
name: T
}
interface BmwMetadata {
foo: number
}
interface AudiMetadata {
bar: number
}
interface CarBase<T = BrandName, M = null> {
brand: Brand<T>
metadata: M
}
type Bmw = CarBase<'bmw', BmwMetadata>
type Audi = CarBase<'audi', AudiMetadata>
type Ford = CarBase<'ford'>
export type Car = Bmw | Audi | Ford
const test = (car: Car) => {
if (car.brand.name === 'bmw') {
return car.metadata?.foo // <-- error
}
if (car.brand.name === 'audi') {
return car.metadata?.bar // <-- error
}
return false
}