What is ts-reset ?
ts-reset
is an open-source package that provides a set of rules that modify TypeScript's built-in typings. It makes them more strict, more consistent, and more ergonomic. Using ts-reset
can help you avoid subtle bugs caused by type errors, and make your code more readable, maintainable and especially more coherent. Think of it as a Typescript version of css-reset.
ts-reset
was created by Matt Pocock, who also created Total Typescript, a set of workshops to help you become a "Typescript Wizard". Check it out if you wish to master Typescript, totally worth it!
The problem with Typescript's built-in typings
TypeScript's built-in typings are pretty good, but they're not perfect. They're based on a set of assumptions about how code should work, and those assumptions don't always match reality.
A few examples of the problems you might encounter when working with TypeScript:
.json
(infetch
) andJSON.parse
both returnany
instead ofunknown
.filter(Boolean)
doesn't behave how you expectarray.includes
often breaks on readonly arrays
These are just a few examples, but they illustrate the kinds of issues that can crop up when working with TypeScript's built-in typings.
The solution: ts-reset
ts-reset
fixes Typescript in a lot of ways. The package provides several rules that you can import globally or individually to make Typescript's built-in typings more strict and coherent. Check out the examples below:
// BEFORE
const result = JSON.parse("{}"); // any
// AFTER ts-reset
const result = JSON.parse("{}"); // unknown
// BEFORE
const filteredArray = [1, 2, undefined].filter(Boolean); // (number | undefined)[]
// AFTER ts-reset
const filteredArray = [1, 2, undefined].filter(Boolean); // number[]
You can find the full list of rules in the package's repository.
How to use ts-reset
Getting started with ts-reset
is quite easy:
-
Install the package
npm i -D @total-typescript/ts-reset
-
Create a
reset.d.ts
file in your project with the following codeimport "@total-typescript/ts-reset"; // OR if you wish to include only certain rules, import them individually // Makes JSON.parse return unknown import "@total-typescript/ts-reset/json-parse"; // Makes await fetch().then(res => res.json()) return unknown import "@total-typescript/ts-reset/fetch";
- Have fun with an improved version of Typescript
Keep in mind that you need to set module
to NodeNext
or Node16
in your tsconfig.json
Don't forget to read the README in the repository: ts-reset
is designed to be used in application code, not library code. Meaning that if you include these rules in your library, your users will automatically be using ts-reset
rules independently of their will.