Why isn't typescript validating the parameter argument?
You can make TypeScript only accept objects by concatenating your type with a type object
:
function fancyMethod({ option1 = true }: { option1?: boolean } & object = {}) {
console.log(option1);
}
fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
fancyMethod({}); // no error
source to share
So the type of the argument fancyMethod
is that there must be an object with an optional boolean property option1
.
All of the parameters you passed are objects that don't have a property option1
, but that's ok as it is optional, so you only get the option1 = true
default in each case .
A shorter example that shows the same:
let x: { option1?: boolean } = "abc";
x = 42;
Both the string and number are compatible with a type in which all properties are optional.
However, if you try now:
x = { foo: 1 };
you will get an error:
t.ts(11,7): error TS2322: Type '{ foo: number; }' is not assignable to type '{ option1?: boolean | undefined; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ option1?: boolean | undefined; }'.
because there is an additional check if you are passing an object literal with properties that are not part of that type, and this happens if you try to pass an object literal with additional properties to fancyMethod()
source to share