TypeScript 4.7: New Features and Improvements
TypeScript 4.7: New Features and Improvements
TypeScript 4.7 brings significant improvements to module resolution, type inference, and developer experience.
ECMAScript Module Support
package.json exports
{
"name": "my-package",
"type": "module",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
}
}
Module Resolution
// tsconfig.json
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
}
Instantiation Expressions
// Before
const StringMap = Map<string, string>;
// Now with instantiation expressions
const StringMap = Map<string, string>;
function makeBox<T>(value: T) {
return { value };
}
// Create specialized versions
const makeStringBox = makeBox<string>;
const makeNumberBox = makeBox<number>;
extends Constraints on infer
// More precise type inference
type FirstIfString<T> = T extends [infer S extends string, ...unknown[]]
? S
: never;
type A = FirstIfString<['hello', number]>; // 'hello'
type B = FirstIfString<[number, string]>; // never
// Pattern matching with constraints
type ExtractNumber<T> = T extends (infer N extends number)[] ? N : never;
type Nums = ExtractNumber<[1, 2, 3]>; // 1 | 2 | 3
Optional Variance Annotations
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
// Covariant - accepts T or subtypes
type Getter<out T> = () => T;
// Contravariant - accepts T or supertypes
type Setter<in T> = (value: T) => void;
// Invariant - only accepts T
type Box<in out T> = {
get: () => T;
set: (value: T) => void;
};
Resolution Mode Declarations
import type { Type } from "module";
import type { Type as Alias } from "module";
import type * as Types from "module";
// Resolution mode imports
import type { Type } from "module" with { "resolution-mode": "import" };
import type { Type } from "module" with { "resolution-mode": "require" };
Improved Control Flow
function foo(a: string | number, b: boolean | string) {
const equals = a === b;
if (equals) {
// TypeScript now knows both are strings
a.toUpperCase(); // OK!
b.toUpperCase(); // OK!
}
}
// Improved narrowing
function f(x: unknown) {
if (typeof x === 'object' && x !== null) {
x; // Object in 4.7, not {} | null
}
}
Object Method Syntax
const obj = {
method<T>(x: T): T {
return x;
}
};
// Works with computed properties
const key = 'computed';
const obj2 = {
[key]<T>(x: T): T {
return x;
}
};
Type Aliases in extends
type Animal = {
name: string;
};
// Can now extend type aliases
interface Dog extends Animal {
breed: string;
}
Performance Improvements
- Faster incremental builds
- Better memory usage
- Improved type checking speed
Breaking Changes
- Stricter spread checks
- Changes to infer behavior
- Module resolution changes
Conclusion
TypeScript 4.7 brings important improvements for modern JavaScript development, especially around ESM support and type inference precision.