What is new for TypeScript 4.6?
Here’s a summary of what is new to TypeScript 4.6.
Allowing Code in Constructors Before super()
There are changes to type checking in constructor of class. Normally, there are errors if there are code before super()
is called. Now, it’s more lenient! Code is allowed to run before super()
and there’s still going to be errors if this
is called before super()
.
Control Flow Analysis for Destructured Discriminated Unions
Before 4.6, TypeScript would error if we try to narrow type in control flows with destructured variables. For instance,
const action = { type: 'A', provider: 3 };
const {type, provider} = action;
if (type === 'A') {
// ...
} else if (type === 'B') {
// ...
}
Now, we can narrow types based on discriminant property for destructured variables.
Improved Recursion Depth Checks
Improve recursion depth checks for deeply-nested types by distinguishing between the nesting is generated through exploring types vs developer written. This concludes type is infinitely expanding much earlier and save work on checking for compatibility.
Indexed Access Inference Improvements
Improve typings for indexed access types applied to mapped types. For instance, a union of types that are in the same map.
type UnionRecord =
| { kind: "n", v: number, f: (v: number) => void }
| { kind: "s", v: string, f: (v: string) => void }
| { kind: "b", v: boolean, f: (v: boolean) => void };
function processRecord(rec: UnionRecord) {
rec.f(rec.v); // Error, 'string | number | boolean' not assignable to 'never'
}
Now, this is inferred properly!
Control Flow Analysis for Dependent Parameters
You can use rest parameter with type of discriminated union of tuples. Then you can narrow parameters.
type args = ['A', number] | ['B', string];
—target es2022
--target
option supports es2022
. This means:
- class fields have stable output target preserved
- we can use
- at() on Arrays
- Object.hasOwn
- cause option in new Error
Removed Unnecessary Arguments in react-jsx
Remove void 0
arg and improve bundle size for compiling in —jsx react-jsx
JSDoc Name Suggestions
TypeScript now gives suggestions when parameter names & JSDoc comment doesn’t match.
More Syntax and Binding Errors in ## JavaScript
New errors in JavaScript files even if we don’t turn on CheckJs
or add @ts-check
. We can disable these with @ts-nocheck
.
TypeScript Trace Analyzer
We can use --generateTrace
flag to identify expensive types.
Breaking Changes
- when we use rest now, it drops unspreadable members from generic objects
- so
const { x, ...rest } = y;
, rest will not contain x now.
- so
- JavaScript files always get grammer & binding errors unless we specified
@ts-nocheck