Typescript Basics
Typescript is a superset of JavaScript that gives you types for the compiler to catch type related errors.
Instant type error detection, Better IDE experience, More self-documenting code, More readable & easier to understand
When to use Typescript
- When you have a large codebase
- Accustomed to statically typed languages
When should I use TypeScript? (freecodecamp.org)
Migrating
If you already have a JavaScript project you can use ts-migrate to change file extensions based on a folder or all at once. Within each file it will add comments for errors that must be fixed. In react it will need to know to expect jsx. In node express applications it will need to express types.
Typescript React Conversion Guide
Basics
These examples are taken from this repo.
Variables declared and set to a value already have a type.
Set types using variableName: type
Interfaces can be used to create custom types. You can still do OR and AND operands as types using | and & respectively.
Async functions must be returned as Promise generic,
export const addTwoNumbers = (a: number, b: number) => {
return a + b;
};
interface User {
id: number;
firstName: string;
lastName: string;
role: "admin" | "user" | 'super-admin';
}
export const fetchLukeSkywalker = async (): Promise<LukeSkywalker> => {
const data = await fetch("https://swapi.dev/api/people/1").then((res) => {
return res.json();
});
return data;
};
You can extend interface to avoid repeating yourself.
interface Base {
id: string;
}
interface User extends Base {
firstName: string;
lastName: string;
}
Omit can omit part of a type. Pick can use only selected parts of a type.
type MyType = Pick<User, "firstName" | "lastName">;
type MyType2 = Omit<User, "id">;
You can create function type, params, and define the return type of a function.
const functions = {createUser: () => Promise<string>,
getUser: (id: string) => Promise<User>};
const makeUser = (): User => {...
TypeScript: Documentation — TypeScript for JavaScript Programmers (typescriptlang.org)