Typescript
up:: JavaScript
Ressources
Why Typescript
- Type checking
- Code completion
- Additional features
When to use TS
- Just use enough Types to be helpful
- Think about types more as documentation rather than βtypescript all the thingsβ
- What is good about Typescript is that it adds auto-completion
Types
- Typescript any
- TypeScript Tuples
- TypeScript enum
- Typescript objects
- TypeScript Union Types TypeScript Functions
Function
Type alias
type Employee = {
readonly id: number,
name: string,
}
Namespaces
global.d.ts
is a global namespace
Defining type
Interfaces
Interfaces are basically type definitions for objects.
interface Restaurant {
name: string;
rating: string;
diet: dietOptions;
}
In order to make an interface βloop-ableβ, we need to specify the key:
interface Tag {
[key: string]: string | undefined; // return value from the key is either a `string` (since all values are strings), or `undefined` (since some keys are optional)
tag: string;
icon: string;
from?: string;
to?: string;
fromDark?: string;
toDark?: string;
}
Type
Defining a type
looks a bit like defining a variable with let
. By convention, they are UpperCamelCased.
type MyStringType = string;
let s: MyStringType = 'hello';
Prefer interfaces
According to the documentation, it is best practice to prefer using interfaces and only use type when specific features are required.
type dietOptions = "Vegetarian" | "Vegan" | "Pescetarian"
Type Erasure
The types are only checked while compiling and then βthrown awayβ. Typescript checks all the type-specific syntax and then compiles into pure JavaScript.
Letβs take a line like this:
type MyNumberType = number;
All the Typescript syntax gets evaluated and then erased. That leaves zero JavaScript to be compiled. When running the program, it returns undefined
.
Summary
JavaScript: syntax check β execution. TypeScript: syntax check β type check β execution.
Get the return type of a function
This is handy when initialising a variable.
let wrapper: ReturnType<typeof mount>;