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
1.8k views
in Technique[技术] by (71.8m points)

typescript - Is it possible to define an interface/type to which excess property checks are always applied?

In TypeScript, excess property checks are applied to object literals, but not beyond that. (This is intentional documented behavior.) So given:

interface Example {
    id: number;
    name: string;
}
// ...
function doSomething(ex: Example) {
    // ...
}

This fails (playground link):

doSomething({
    id: 42,
    name: "Life, the Universe, and Everything",
    extra: "not allowed" // Error 2345: Object literal may only specify known properties, and 'extra' does not exist in type 'Example'.
});

but this doesn't (playground link):

const ex = {
    id: 42,
    name: "Life, the Universe, and Everything",
    extra: "not allowed"
};
doSomething(ex);

Is it possible to define the interface in some way that excess properties are forbidden even when not using an object literal? E.g., a "final" interface of sorts?

If not, it's easily done at runtime, but if there's a way to do it in the type definition, that would be useful.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What you are looking for is exact types. This feature has been in discussion since forever on GH but it has not come any closer to actually being implemented. The concern is (at least from what I heard at tsConf from Anders) is that exact types would create a bifurcated type system, where you could not assign from exact to inexact types and backwards, and this would make the dev experience much worse.

There are work arounds, but all are flawed in some way, you can read the GH issue to find all sorts of versions that might work well enough depending on what you are trying to do.


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

1.4m articles

1.4m replys

5 comments

56.5k users

...