-2

Why does the following piece of code not throw a type error?

const fn1 = (arg1: { key: number }) => {
  console.log(arg1);
}

// Works as expected
fn1({ key: 1 });

// But this gives no type error
fn1({ key: 1, a: 1 });

I have read typescipt docs and google for some time , can't understand the scene!

CoderApprentice
  • 425
  • 1
  • 6
  • 21

1 Answers1

0

Typescript does not throw an error because the input type { key: number } is a minimum requirement, not a precise requirement. So if you throw in { key: 1, a: 1 } there is no error, because it contains the key property, and that's enough.

If you throw in { a: 1 }, then there is an error, because the minimum requirement is to have the key property.

If you want TypeScript to throw an error, then you could create a class or an interface instead.

class ExampleClass {
  constructor(readonly key: number) {}
}

interface ExampleInterface {
  key: number;
}

const fn1 = (arg1: ExampleClass | ExampleInterface) => {
  console.log(arg1);
}

// Now TypeScript will notify you of an error
fn1({ key: 1, a: 1 });

// But this won't.
fn1(new ExampleClass(1));
fn1({ key: 1 });
CoderApprentice
  • 425
  • 1
  • 6
  • 21