Object types in TypeScript are open/extendible, not closed/exact. That means it's acceptable for an object of type X
to contain more properties than the definition of X
mentions. You can think of object type definitions as describing the known properties of the type, while having no implications about possible unknown properties.
This openness is important because it allows interface extension and class inheritance. Your type definitions are nearly identical to
interface Payload {
id: number;
}
interface GreatPayload extends Payload {
surprise: 4;
}
And here you can see that GreatPayload
is a special type of Payload
. It has an extra property, but it's still a Payload
. Same thing with class inheritance:
class Foo {
a = "foo";
}
class Bar extends Foo {
b = "bar";
}
A Bar
instance is a Foo
:
const f: Foo = new Bar(); // okay
The only place where the TypeScript compiler treats object types as if they were exact is when you create a brand new object literal and assign it to a type. This is documented in the TypeScript Handbook as "Excess Property Checks"... and you can also look at microsoft/TypeScript#3755, the GitHub issue that discusses the need for this behavior; misspelling optional properties would be completely uncaught errors without some sort of key checking like this. But it's not a full implementation of exact types.
So when you call this:
action({ id: 1, surprise: 4 }); // error
you are passing in a fresh object literal that contains an unexpected surprise
property, and the compiler warns via excess property checks. But when you call this:
action(payload); // okay
you are passing in the variable payload
, which is not an object literal itself, and the object literal you assigned to payload
is no longer "fresh". So no excess property checks happen and you get no warning.
If you really want to see exact types implemented so that you could easily ask for Exact<Payload>
, you might want to go to microsoft/TypeScript#12936 and give it a ??, and possibly even describe your use case if it's particularly compelling.
But given that the current behavior is probably not going anywhere for a while, your time might be better spent trying to work with open types instead of against them. Consider writing your code so that it doesn't mind if an object has more properties than specified in the type declaration. If you're just indexing into the object with known keys, you'll be fine. If you're iterating through object properties, don't use Object.keys()
or for..in
loops if your code would explode on unexpected properties. Instead, think about iterating through known keys from a hardcoded array (see this answer for one way to do this). The idea is to make your code immune to unknown extra properties so that you don't care if someone gives you a GreatPayload
when you're expecting just a Payload
.
Okay, hope that helps; good luck!
Playground link to code