I imagined this code
let x: (a: { b: number }) => void = (a: { b: number, c: string }) => { alert(a.c) };
x({ b: 123 });
should produce an error, since the lambda function requires an additional property on the a
argument, so the signatures should not be compatible. But trying this in the latest typescript playground does not produce any errors! Why is that?
When you said
let x: (a: { b: number }) => void
You are saying "x is a function that takes an object with a b
key."
You then assigned it a lambda that took an object with a b
key and a c
key. That passes the typechecker because any object that gets passed in must have a b
key.
Then you pass it an object with a b
key. There's no error.
If you want it to fail because of the c
key, make the type of x
the following:
let x: (a: { b: number, c: string }) => void
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.