In TypeScript, if I define an interface MyInterface such as:
interface MyInterface {
a ?: string;
}
And if I define a function myFunction that only accepts a parameter of type MyInterface such as:
function myFunction(parameter: MyInterface) {
console.log("hello!")
}
If I define an object myObject
let myObject = {
a: "lol",
b: "hi"
}
And call myFunction with myObject as a parameter myFunction(myObject) TypeScript gives no errors.
But if I call myFunction with an object literal as a parameter with the same data as myObject
myFunction({a: "lol", b: "hi"}) TypeScript gives the following error:
Argument of type '{ a: string; b: string; }' is not assignable to parameter of type 'MyInterface'.
Object literal may only specify known properties, and 'b' does not exist in type 'MyInterface'.(2345)
Why doesn't this error appear when I call myFunction with the object variable ?