I'm trying to understand the extent of the typesafety offered by Typescript. I've come across a scenario where I expect an error, but Typescript doesn't complain.
I've defined a function with a parameter matching a certain interface. Then I call the function with some arguments which don't match. Here's the code (or in playground):
interface ArgumentInterface {
[key: number]: string
}
interface InvalidArgumentInterface {
[key: string]: number
}
interface InvalidArgumentInterface2 {
foo: number
}
function myFunction(arg: ArgumentInterface) {
// function body
}
let validArgument: ArgumentInterface = {};
validArgument[5] = 'I am a string';
let invalidArgument: InvalidArgumentInterface = {
foo: 42
};
let invalidArgument2: {foo: number} = {
foo: 42
};
let invalidArgument3: InvalidArgumentInterface2 = {
foo: 42
};
let invalidArgument4 = {
foo: 42
};
myFunction(validArgument); // no typescript error, as expected
myFunction(invalidArgument); // typescript error, as expected
myFunction(invalidArgument2); // no typescript error!
myFunction(invalidArgument3); // typescript error, as expected
myFunction(invalidArgument4); // no typescript error!
When my argument variable explicitly declares an incompatible interface, I get a Typescript error as expected. But when my argument variable declares a type literal (without an interface) or declares no type at all, Typescript doesn't complain at all, although I'd expect an error.
I have the "noImplicitAny" flag set to true.
Can anybody explain this behavior?