crashmstr's answer is correct but it's worth explaining why this case is different from one where you do get an error.
Object literals only cause extra property errors in specific cases.
In this case:
var x: MyState = { foo: 10, bar: 20 };
The type system does the following steps:
- Check that MyState is a valid type (it is)
- Check that the initializer is valid:
- What is the type of the initializer?
- It is the fresh object type
{foo: 10, bar: 20}
- Is it assignable to
MyState
?
- Is there a
foo
property?
- Does its type match?
- Are there any extra properties from a fresh type?
The key thing here is freshness. A type from an object literal is fresh if it comes directly from the object literal itself. This means there's a difference between
// Error
var x: MyState = { foo: 10, bar: 20 };
and
// OK
var x1 = { foo: 10, bar: 20 };
var x2: MyState = x1;
because the freshness of the object literal vanished once it was assigned into x1
.
Your example suffers the same fate - the freshness of the object literal is gone once it became part of the function return type. This also explains why the error re-appears if you have a return type annotation on the function expression.