There are various ways to determine if a property exists on an object:
1. To check if an object owns a property, you can use:
if(car.hasOwnProperty('model')) {
// ...
}
2. If you want to confirm if a property is part of the object's prototype
, you can utilize:
if(Object.getPrototypeOf(car).hasOwnProperty('model')) {
// ...
}
Note: car.__proto__.hasOwnProperty
could also work, but it's only consistent since the ECMAScript2015 spec.
3. To verify if a property exists on an object, you can use:
if(car['model']) {
// ...
}
You should also ensure to check its type as typeof Function
before invoking it.
In your particular case, if model
is part of the Car.prototype
, the second option would be suitable. Additionally, you need to inform TypeScript that the car has the model
method because car['model']()
will fail if the noImplicitAny
option is enabled.
if (Object.getPrototypeOf(car).hasOwnProperty('model')) {
if(typeof (car as Car & { model: Function }).model === typeof Function) {
(car as Car & { model: Function }).model()
}
}
For the TypeScript compiler, the
(car as Car & { model: Function }).model()
section is crucial.
Alternatively, you could define your own global type for the experimental Car.model
method:
type ExperimentalCarModel = (details:
{ brand: string, year?: number, color?: string }
| { brand?: string, year: number, color?: string }
| { brand?: string, year?: number, color: string }
) => void;
declare type ExperimentalCar = Car & {
model: ExperimentalCarModel
}