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 });