/
📝

TypeScript

jstypescript
On this page

Migrate an entire project to TypeScript

zsh
npx -p ts-migrate -c "ts-migrate-full ."

Create a condition-based subset types

ts
type SubType<Base, Condition> = Pick<
Base,
{
[Key in keyof Base]: Base[Key] extends Condition ? Key : never;
}[keyof Base]
>;
// or
type FilterFlags<Base, Condition> = {
[Key in keyof Base]: Base[Key] extends Condition ? Key : never;
};
type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];
type SubType<Base, Condition> = Pick<Base, AllowedNames<Base, Condition>>;
// usage
type JsonPrimitive = SubType<Person, number | string>;
type JsonPrimitive = {
id: number;
name: string;
lastName: string;
};

An Introduction To Type Programming In TypeScript

Equality comparisons and conditional branching

In the type language, on the other hand, we use the extends keyword for "equality check", and the conditional (ternary) operator ? for conditional branching too as in:

ts
TypeC = TypeA extends TypeB ? TrueExpression : FalseExpression

The extends keyword is versatile. It can also apply constraints to generic type parameters. For example:

ts
function getUserName<T extends { name: string }>(user: T) {
return user.name;
}

By adding the generic constraints, <T extends {name: string}> we ensure the argument our function takes always consist of a name property of the type string.

How to use type guards in TypeScript

ts
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}

Functions

ts
function fn(a, b = "world") {
return [a, b];
}
const result = fn("hello"); // ["hello", "world"]
ts
type Fn<A extends string, B extends string = "world"> = [A, B];
// ↑ ↑ ↑ ↑ ↑
// name parameter parameter type default value function body/return statement
type Result = Fn<"hello">; // ["hello", "world"]

Typescript utility types

  • keyof: creates a union type consisting of the property names of the type you pass
  • Partial: will return a new type with all of the props set to optional.
  • Pick creates a new type by specifying which properties you would like to copy
  • Omit will copy all the props, except for the ones you passed:
  • Exclude removes a constituent of that union.
  • Record:constructs an object type whose property keys are Keys and whose property values are Type

React with TypeScript: Best Practices

React with TypeScript

Best practices for using Typescript with React

Making ESLint Happy in Mixed TypeScript/Javascript Projects

Add this property to your .eslintrc:

js
overrides: [
{
extends: ["plugin:@typescript-eslint/recommended"],
files: ["**/*.ts?(x)"],
plugins: ["@typescript-eslint"],
},
];

Exploring advanced compiler options in TypeScript

This article will cover the following options:

  • Nested tsconfig.json files
  • strictPropertyInitialization
  • noImplicitThis
  • noImplicitReturns
  • strictNullChecks
sh
├── dist
└── src
├── tsconfig.json
├── backend
│ ├── index.ts
│ └── tsconfig.json
└── frontend
├── index.ts
└── tsconfig.json
json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"rootDir": ".",
"outDir": "../dist/"
},
"files": [],
"references": [{ "path": "./backend" }, { "path": "./frontend" }]
}

Tools

  • Quokka.js: a developer productivity tool for rapid JavaScript / TypeScript prototyping.
  • ts-migrate: A tool to help migrate JavaScript code quickly and conveniently to TypeScript

Tutorials

Type Challenges

  • Pick
ts
type MyPick<T, K extends keyof T> = {
[key in K]: T[key];
};
// ❌ bad one
// Can't determine the return value type
function getValue(o:object, key: string){
return o[key]
}
// ✅ Constrain the input key
function getValue<T extends Object,K extends keyof T>(o: T,key: K): T[K] {
return o[key]
}
const obj1 = { name: 'test', age: 18}
// If the second argument is not an argument in obj1, an error will be reported
const values = getValue(obj1, 'name')
Edit this page
logo
Code-related notes and snippets