Why isn't typescript validating the parameter argument?

Why doesn't typescript show type errors for the following example?

function fancyMethod({ option1 = true }: { option1?: boolean } = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);

      

Try it yourself using this link for playgrounds

+3


source to share


2 answers


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

      

+2


source


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()

+3


source







All Articles