Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't typescript check an option argument?

Tags:

typescript

Why doesn't typescript show any 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 Playground Link

like image 388
jantimon Avatar asked Jan 23 '26 05:01

jantimon


2 Answers

So the type of the argument to fancyMethod is that is must be an object with optionally a boolean property option1.

All of the parameters you passed in are objects that don't have an option1 property but that's alright as it is optional, so in each case you'll just get the default option1 = true.

A shorter example that shows the same thing:

let x: { option1?: boolean } = "abc";
x = 42;

Both the string and the number are compatible with a type where all of the properties are optional.

However, if you now try:

x = { foo: 1 };

you 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 additional checking if you pass in an object literal with properties that are not part of the type, and the same happens if you try to pass an object literal with additional properties to fancyMethod()

like image 118
Duncan Avatar answered Jan 24 '26 21:01

Duncan


You can force TypeScript to accept only objects by merging your type with object type:

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

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
fancyMethod({}); // no error
like image 22
Hoang Hiep Avatar answered Jan 24 '26 22:01

Hoang Hiep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!