When inferring types, TypeScript often errs on the more general side. This may sound counter-intuitive as the existence of TypeScript is based on type safety, which requires TypeScript to be as precise and strict as possible. However, this feature proves to be necessary and extremely useful. It is called Type Widening, a key concept to TypeScriptโs type inference mechanism.
For example, in TypeScript, an absence of something can be represented by either null or undefined. Imagine a situation where a variable has to be declared before its final value is known:
Without Type Widening, as shown in the first half of the example, we would not be able to assign a meaningful value to the variable a at a later stage, rendering it less useful.
Type Widening for Type Literals and Object Literals
The same consideration applies to type literals, including primary type literals and object literals. The following code demonstrates how it works with primary type literals:
With object literals, we introduce a concept called fresh object literal type, referring to the type TypeScript infers from an object literal. The rule states that if an object literal uses a type assertion or is assigned to a variable, it will be widened to a regular object type and is no longer considered fresh.
This is the base of excess property checking, where TypeScript reports an error when you try to assign a fresh object literal type T to another type U and T has extra properties that are not present in U.