TypeScript 3 Features: A Quick Overview


Introduction

TypeScript 3 introduced several new features and improvements that enhance the developer experience and type safety. In this guide, we'll provide a quick overview of some of these features along with sample code to illustrate how they work.


1. Tuple Types

Tuple types allow you to define an array with a fixed number of elements, each with its own type.

let person: [string, number] = ['Alice', 30];
let coordinates: [number, number] = [50, 100];

2. Rest Parameters in Tuple Types

You can use the rest parameter syntax (...) in tuple types to capture remaining elements in an array.

function firstTwoElements(...args: [string, number, ...string[]]) {
const [first, second, ...rest] = args;
console.log('First:', first);
console.log('Second:', second);
console.log('Rest:', rest);
}
firstTwoElements('Alice', 30, 'Bob', 'Charlie', 'David');

3. Spread in Tuple Types

The spread syntax (...) can be used to split tuple elements into individual variables.

const coordinates: [number, number] = [50, 100];
const [x, y] = [...coordinates];
console.log('X:', x);
console.log('Y:', y);

4. Omit Helper

The Omit helper allows you to create a type by omitting specific properties from an existing type.

type Person = {
name: string;
age: number;
email: string;
};
type PersonWithoutEmail = Omit<Person, 'email'>;

5. ReadonlyArray

The ReadonlyArray type ensures that an array cannot be modified after creation.

const numbers: ReadonlyArray<number> = [1, 2, 3];
numbers.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.

Conclusion

TypeScript 3 introduced a variety of features to improve type safety and developer productivity. These features, such as tuple types, rest parameters in tuple types, the Omit helper, and ReadonlyArray, provide developers with powerful tools to write safer and more maintainable code. Understanding and using these features can help you take full advantage of TypeScript in your projects.