TypeScript 4 Features: What's New in the Language


Introduction

TypeScript 4 introduced several new features and improvements to enhance the language and developer experience. In this guide, we'll provide a detailed overview of some of these features, along with sample code to demonstrate their usage.


1. Variadic Tuple Types

Variadic tuple types allow you to represent tuple types with a variable number of elements.

function mergeArrays<T extends any[][]>(...arrays: T): T[number] {
return ([] as T[number]).concat(...arrays);
}
const merged = mergeArrays([1, 2], [3, 4], [5, 6]);
console.log(merged); // Output: [1, 2, 3, 4, 5, 6]

2. Labeled Tuple Elements

Labeled tuple elements allow you to assign names to tuple elements when destructuring, making code more self-documenting.

type Point = [x: number, y: number];
const point: Point = [10, 20];
const [x, y] = point;
console.log(x, y); // Output: 10 20

3. Template Literal Types

Template literal types allow you to define and manipulate string literal types using template strings.

type Color = 'red' | 'green' | 'blue';
type ColorHexMap = {
[K in Color]: `#${Uppercase<K>}`;
};
const colors: ColorHexMap = {
red: '#FF0000',
green: '#00FF00',
blue: '#0000FF',
};
console.log(colors.red); // Output: #FF0000

4. keyof and Lookup Types

The `keyof` operator and lookup types allow you to work with keys of objects and access the corresponding value types.

type Person = {
name: string;
age: number;
};
type PersonKeys = keyof Person;
type PersonValue = Person[PersonKeys];
const person: Person = {
name: 'Alice',
age: 30,
};
const key: PersonKeys = 'name';
const value: PersonValue = person[key];
console.log(key, value); // Output: "name" "Alice"

5. Optional Chaining and Nullish Coalescing

TypeScript 4 introduced support for optional chaining (`?.`) and nullish coalescing (`??`) operators to safely navigate and handle potentially null or undefined values.

const user = {
name: 'Alice',
address: {
city: 'Wonderland',
},
};
const cityName = user.address?.city;
const missingData = user.address?.missingProperty ?? 'Unknown';
console.log(cityName); // Output: "Wonderland"
console.log(missingData); // Output: "Unknown"

Conclusion

TypeScript 4 brought several new features and improvements to the language, enhancing developer productivity and code safety. Features like variadic tuple types, labeled tuple elements, template literal types, `keyof` and lookup types, and optional chaining and nullish coalescing provide developers with powerful tools to write cleaner and more robust code. Understanding and using these features can help you take full advantage of TypeScript in your projects.