It seems like you already have the knowledge that 'Brand'
is part of the Car
object at compile time. So, why would you need to check for it?
If the type is not fully known, perhaps in a type argument scenario, then attempting something like this could be considered...
function<T>(foo: T) {
// This won't work since 'keyof' doesn't exist in runtime environments
if('bar' in keyof T) {
// do something...
}
}
Instead of comparing against keyof T
, try a different approach like below...
interface Car {
Brand: string;
Model: string;
}
interface Bus {
Passengers: number;
Color: string;
}
function(foo: Car | Bus) {
if('Brand' in foo) {
// It's a Car
} else {
// It's a Bus
}
}
If working with keys is your goal, consider this alternative...
type CarKey = keyof Car;
const carKeys: CarKey[] = ['Brand', 'Model'];
function(key: string) {
if(carKeys.includes(key)) {
// perform action
}
}
To ensure you have all keys covered, here's a more thorough method...
type CarKey = keyof Car;
const carKeys = Object.keys({
Brand: null,
Model: null
} satisfies Record<CarKey, null>) as Array<keyof Car>;
function isKeyOfCar(key: string): key is CarKey {
return carKeys.includes(key);
}
This way, any future changes to the Car
type will prompt updates to these key checks.