In the following code...
interface Options {
allowed?: string;
}
function test(options: Options) {
return options;
}
const options = {
allowed: 'allowed',
notAllowed: 'notAllowed',
};
test(options); // does not throw an error
Why is adding notAllowed
to options
not throwing an error in Typescript when calling test(options)
?
How can I write this so excess properties are disallowed?
EDIT 1...
I can get Typescript to throw an error if I rewrite it to const options: Options = {...};
.
However, shouldn't typescript infer this because I've specified that the options parameter in the function should be of type Options?
If not, shouldn't typescript throw an error when trying to pass in const object = {...};
?
Otherwise, this isn't very useful for other developers passing in their own objects into the test
function.
EDIT 2...
The reason I want this is for option bags where I don't want developers to misspell a property. For instance, I want them to be able to provide an include
property and disallow the includes
property. Is the only way to make this happen when they pass in an object variable (instead of an object literal) as a parameter in the test
function is to declare a property on the Options
interface includes?: null;
or something like that?