https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
type MyObject = {
foo: string;
bar: string;
baz: string;
};
type MyOtherObject = {
foo: string;
};
declare const myObject: MyObject;
// Omit + rest
// Oops, we forgot to omit a prop (`baz`).
const { bar, ...restProps } = myObject;
const myOtherObject: MyOtherObject = {
// No excess error :-(
...restProps
};
This is particularly problematic when spreading props into a React component, as it can hurt performance or create invalid HTML: microsoft/TypeScript#31798.
Instead of using "omit + rest" (above), "pick":
// Pick
const myOtherObject: MyOtherObject = {
foo: myObject.foo,
// Excess error :-)
baz: myObject.baz
};
type A = {};
const a: A = { a: 1 };
https://stackoverflow.com/questions/42537727/empty-interface-allow-any-object
type Fn = () => {
foo: string;
};
const fn: Fn = () => ({
foo: "foo",
// No excess error :-(
bar: "bar"
});
Annotate function return type or use constructor
type FnResult = {
foo: string;
};
type Fn = () => FnResult;
const fn: Fn = (): FnResult => ({
foo: "foo",
// Excess error :-)
bar: "bar"
});
- microsoft/TypeScript#30631
- microsoft/TypeScript#20863
- https://stackoverflow.com/questions/52677576/typescript-discriminated-union-allows-invalid-state/52678379#52678379
- https://paper.dropbox.com/doc/WTF-TypeScript--Ah9g0XR_kPNPm0rA9z95YRg4Ag-fyxWXDfqYssUzsAzmGmZL#:h2=Problem-2:-Union-types-are-not
- "Exact types" could help? microsoft/TypeScript#12936
- The TS team would prefer to improve excess property checks than introduce exact types: microsoft/TypeScript#12936 (comment)