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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…