Within my code, I have an unidentified object containing a property with TypeScript type. Here is an example:
type Bar = {
exists: true;
baz: string;
};
performAction({
bar: {
exists: true,
baz: 'qux',
} as Bar,
});
I am seeking a way to safeguard the bar
property so that if the type Bar
were to change in the future (e.g. additional property), TypeScript would generate a warning. The following instances should trigger compiler errors:
performAction({
bar: {
exists: 'string', // Incorrect data type
baz: 'qux',
} as Bar
});
performAction({
bar: {
something: 'hey', // Insufficient match with Bar
baz: 'qux',
} as Bar
});
In this scenario, there is no type error even though exists
is absent:
performAction({
bar: {
baz: 'qux',
} as Bar
});
Similarly, this also does not produce a type error:
performAction({
bar: <Bar>{
baz: 'qux',
},
});
The only method I currently know to prompt a type error when a Bar
property is missing involves:
const bar: {bar: Bar} = {
bar: {
baz: 'qux',
},
};
performAction(bar);
However, this approach necessitates creating a local variable solely for enforcing type safety. Is there a technique to safeguard an anonymous object property with type protection?
As a note, the parameter accepted by performAction()
permits any type and does not enforce specific requirements, which eliminates the option of relying on performAction
for type enforcement.