Exploring the code snippet...
interface Options {
allowed?: string;
}
function test(options: Options) {
return options;
}
const options = {
allowed: 'allowed',
notAllowed: 'notAllowed',
};
test(options); // no error thrown
Why does adding notAllowed
to options
not result in an error in Typescript when calling test(options)
?
Is there a way to modify this to disallow excess properties?
UPDATE 1...
If I change it to const options: Options = {...};
, Typescript will raise an error.
Shouldn't Typescript automatically infer this since I specified that the options parameter should be of type Options?
If not, shouldn't there be an error when passing in const object = {...};
?
If not, this could lead to issues for other developers using their own objects with the test
function.
UPDATE 2...
The reason for this is to prevent errors in option bags caused by misspelled properties. For example, allowing only include
and excluding includes
. Is the only solution when passing an object variable (not a literal object) as a parameter to declare a property like includes?: null;
in the Options
interface?