Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

javascript - Why does TypeScript not throw an error when the function argument type is mismatched?

Here's a very basic example to demonstrate what I mean:

type Payload = {
    id: number;
}

type GreatPayload = {
    id: number;
    surprise: 4;
}

type Action = (payload: Payload) => void;

const action: Action = payload => null;

const payload: GreatPayload = {
    id: 1,
    surprise: 4,
};

action({ id: 1, surprise: 4 }); // <== as expected, this errors out because `surprise` is not present in `Payload`

action(payload); // <== my question is, why does this not throw an error?

(And the TypeScript playground link for an editable example.)

Why does action(payload) not throw an error when the type of payload that's passed in (GreatPayload) is clearly a mismatch for the function argument type Payload?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...