You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Item 11: Distinguish Excess Property Checking from Type Checking
Things to Remember
When you assign an object literal to a variable with a known type or pass it as an argument to a function, it undergoes excess property checking.
Excess property checking is an effective way to find errors, but it is distinct from the usual structural assignability checks done by the TypeScript type checker. Conflating these processes will make it harder for you to build a mental model of assignability. TypeScript types are not "closed" (pass:[Item 4]).
Be aware of the limits of excess property checking: introducing an intermediate variable will remove these checks.
A "weak type" is an object type with only optional properties. For these types, assignability checks require at least one matching property.
Code Samples
interfaceRoom{numDoors: number;ceilingHeightFt: number;}constr: Room={numDoors: 1,ceilingHeightFt: 10,elephant: 'present',// ~~~~~~~ Object literal may only specify known properties,// and 'elephant' does not exist in type 'Room'};
interfaceOptions{title: string;darkMode?: boolean;}functioncreateWindow(options: Options){if(options.darkMode){setDarkMode();}// ...}createWindow({title: 'Spider Solitaire',darkmode: true// ~~~~~~~ Object literal may only specify known properties,// but 'darkmode' does not exist in type 'Options'.// Did you mean to write 'darkMode'?});
interfaceLineChartOptions{logscale?: boolean;invertedYAxis?: boolean;areaChart?: boolean;}functionsetOptions(options: LineChartOptions){/* ... */}constopts={logScale: true};setOptions(opts);// ~~~~ Type '{ logScale: boolean; }' has no properties in common// with type 'LineChartOptions'