Skip to main content






Install locally, don't use a global install:

npm install --save-dev typescript
npm i -D typescript
yarn add --dev typescript

If we install it locally in our project, we can run that version using npx or yarn:

npx tsc
yarn tsc


Use --noEmit to only typecheck, without outputting JS files:

npx tsc --noEmit
yarn tsc --noEmit

It's common to have a 'typecheck' script on package.json:

"scripts": {
"typecheck": "tsc --noEmit",

Run it with npm run typecheck.

Run tsc on a specific files:


TSConfig Reference:

Create tsconfig.json: npx tsc --init or yarn run tsc --init.

tsconfig.json options to enable

"noImplicitReturns": true /* Report error when not all code paths in function return a value. */

Share tsconfig.json

├── tsconfig-base.json
├── server/
│ ├── tsconfig.json
├── client/
│ ├── tsconfig.json
// tsconfig-base.json
"compilerOptions": {
"exclude": [],
"include": []

// server/tsconfig.json or client/tsconfig.json
"extends": "../tsconfig-base.json",
"compilerOptions": {
"include": []

"strict": true

Setting strict to true in tsconfig.json (or using the tsc --strict flag) enables all this compiler options:

  1. alwaysStrict
  2. noImplicitAny
  3. noImplicitThis
  4. strictBindCallApply
  5. strictFunctionTypes
  6. strictNullChecks
  7. strictPropertyInitialization
  8. useUnknownInCatchVariables

To know which checks are enabled by 'strict' search for 'true if strict' here:



ts-ignore or ts-expect-error?

In some ways // @ts-expect-error can act as a suppression comment, similar to // @ts-ignore. The difference is that // @ts-ignore will do nothing if the following line is error-free.

You might be tempted to switch existing // @ts-ignore comments over to // @ts-expect-error, and you might be wondering which is appropriate for future code. While it’s entirely up to you and your team, we have some ideas of which to pick in certain situations.

Pick ts-expect-error if:

  • you’re writing test code where you actually want the type system to error on an operation
  • you expect a fix to be coming in fairly quickly and you just need a quick workaround
  • you’re in a reasonably-sized project with a proactive team that wants to remove suppression comments as soon affected code is valid again

Pick ts-ignore if:

  • you have a larger project and new errors have appeared in code with no clear owner
  • you are in the middle of an upgrade between two different versions of TypeScript, and a line of code errors in one version but not another.
  • you honestly don’t have the time to decide which of these options is better.

null or undefined?

Douglas Crockford: pick undefined, avoid null -

Gotcha. If we use undefined we don't get an error if we forget to initialize a field in a class constructor, but if we use null we do:

class User {
name: string | null // GOOD - TS2564: Property 'country' has no initializer and is not definitely assigned in the constructor.
country: string | undefined // BAD - No error :(

constructor(name: string | undefined, country: string | null) {
// We forgot to initialize the fields here:
// = name
// = country

Excess property checking

For object literals.

type User = {
id: number
name: string

const user: User = {
id: 1,
name: 'Anna',
password: 'abcd', // <- error
// TS2322: Type '{ id: number; name: string; password: string; }' is not assignable to type 'User'.
// Object literal may only specify known properties, and 'password' does not exist in type 'User'.

function printUser(user: User) {

id: 1,
name: 'Anna',
password: 'abcd', // <- Same error as above

// Note that it doesn't work if we define an intermediate variable:
const data = {
id: 1,
name: 'Anna',
password: 'abcd',
const user: User = data // No error here

Can be disabled:

Make switch exhaustive

* Use it to ensure that a switch is exhaustive.
* From
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function assertUnreachable(switchParameter: never): never {
throw Error('Unreachable code violation')


type Char = 'A' | 'B' | 'C'

function doSomething(char: Char): void {
switch (char) {
case 'A':
case 'B':
// case 'C' is missing
// TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.

Here there are some ideas:


Arrow function property vs method


class MyClass {
name = 'MyClass'
getName = () => {

This will use more memory, because each class instance will have its own copy of each function defined this way

Also see

Exclude methods from classes

class Folder {
name: string
isPublic: boolean

constructor(name: string, isPublic: boolean) { = name
this.isPublic = isPublic

// There are 3 ways to add an instance "method"

// Method - folder.isPrivate()
isPrivate(): boolean {
return !this.isPublic

// Field - folder.isPrivate()
isPrivate = () => {
return !this.isPublic
// We can specify the type:
isPrivate: () => boolean = () => {
return !this.isPublic

// Getter - folder.isPrivate
get isPrivate(): boolean {
return !this.isPublic

// All 3 options trigger this error:
// TS2741: Property 'isPrivate' is missing in type '{ name: string; isPublic: false; }' but
// required in type 'Folder'.
const folder: Folder = {
name: 'Documents',
isPublic: false,

// We can exclude the methods with:
type ExcludeFunctionProperties<T> = Omit<
{ [K in keyof T]-?: T[K] extends Function ? K : never }[keyof T]

// The resulting type is {name: string, isPublic: boolean} if `isPrivate` is defined
// with a method or field, but will be {name: string, isPublic: boolean, isPrivate: boolean}
// if defined with the getter (so don't use getters!).
type FolderNoFunc = ExcludeFunctionProperties<Folder>

// No error "Property 'isPrivate' is missing..." here :)
const folderNoFunc: FolderNoFunc = {
name: 'Documents',
isPublic: false,

// TS2339: Property 'isPrivate' does not exist on type 'FolderNoFunc'.

// We can use a Folder where it expects a FolderNoFunc, since a Folder has more properties:
function printFolderNoFunc(folderNoFunc: FolderNoFunc) {}
printFolderNoFunc(folder) // OK :)
// But we can't use FolderNoFunc where it expects Folder, we get the error:
// TS2345: Argument of type 'FolderNoFunc' is not assignable to parameter of type 'Folder'.
// Property 'isPrivate' is missing in type 'FolderNoFunc' but required in type 'Folder'.
function printFolder(folder: Folder) {}
printFolder(folderNoFunc) // Error :(

Type guards / type narrowing

A user-defined type guard is a function whose return type is a type predicate.

export function isLoading<T>(arg: 'loading' | T | Error): arg is 'loading' {
return arg === 'loading'

export function isSuccess<T>(arg: 'loading' | T | Error): arg is T {
return arg !== 'loading' && !(arg instanceof Error)

export function isError<T>(arg: 'loading' | T | Error): arg is Error {
return arg instanceof Error

Assertion functions

export function assertUser(user: User | undefined): asserts user is User {
if (!user) {
throw new Error('User is undefined')

function doSomething(user: User | undefined) { // TS2532: Object is possibly 'undefined'.
const u: User = user // TS2322: Type 'User | undefined' is not assignable to type 'User'.
// user is now just User, not User | undefined // No error
const u: User = user // No error

Result<T, E> type

interface Loading {
kind: 'loading'

interface Success<T> {
kind: 'success'
data: T

interface Error<T> {
kind: 'error'
error: T

type Result<S, E> = Loading | Success<S> | Error<E>

type GetProductResult = Result<Product, 'network-error' | 'product-not-found'>

const assertions



Issue proposing this:

Pull request:

Improvement example in Next.js:

How TypeScript 4.9 satisfies Your Prisma Workflows:

Utility Types

Make fields optional: Partial<User>. Example: Partial<{ email: string; password: string }> is {email?: string, password?: string}

Make fields required: Required<SomeType>. Is the opposite of Partial.

Return type of an async function:

typescript-eslint ban-types

I prefer {} over Record<string, never> for an empty object because it triggers an error sooner.

const a: {} = {}
a.x // Error TS2339: Property 'x' does not exist on type '{}'.

const b: Record<string, never> = {}
b.x // It's just 'never' but no error is shown yet :/
b.x.y // Error TS2339: Property 'bye' does not exist on type 'never'.

To use {} suppress the rule with // eslint-disable-next-line @typescript-eslint/ban-types.