TypeScript
JavaScript
+
statiske typer
=
TypeScript
function add(a, b) {
return a + b;
}
JavaScript
JavaScript + typer
function add(a: number, b: number): number {
return a + b;
}
TypeError: Cannot read property 'name' of undefined
TypeError: undefined is not a function
Hvorfor?
Autocomplete
Raskere feedback loop
const a: number = 1;
const b: number = 1.5;
const c: string = 'hello';
const d: string = "world";
const e: string = `${c} ${d}`;
const f: boolean = true;
const g: boolean = false;
const h: object = {};
Grunnleggende typer
const myArray: number[] = [1, 2, 3];
const myTuple: [number, number] = [800, 600];
Array og tupler
Type alias
type Point = [number, number];
const myPoint: Point = [35, 100];
type Bounds = [number, number];
const myBounds: Bounds = myPoint;
type Person = {
name: string,
age: number
};
interface Person2 {
name: string;
age: number;
}
Objekt-typer
function siHei(person: Person): void {
alert(`Hei ${person.name}!`);
}
function siHei(person: { name: string, age: number }): void {
alert(`Hei ${person.name}!`);
}
type Numberish = string | number;
type Ternary = 'true' | 'false' | 'maybe';
type PersonFromMessyAPI = {
name: string | undefined | null,
age: number | undefined | null,
};
type Action
= { type: 'SET_VALUE', newValue: number }
| { type: 'INCREMENT' }
;
function doWithAction(action: Action) {
if (action.type === 'INCREMENT') {
action.newValue // Kompileringsfeil
}
if (action.type === 'SET_VALUE') {
action.newValue // OK
}
}
Union-typer
enum Ternary {
FALSE,
TRUE,
MAYBE
}
enum Ternary {
FALSE = "FALSE",
TRUE = "TRUE",
MAYBE = "MAYBE"
}
Enums
type Drivable = {
maxSpeed: number,
}
type Crashable = {
isTotalWreck: boolean,
}
type Turnable = {
turnRadius: number,
}
type Car = Drivable & Crashable & Turnable;
const car: Car = {
maxSpeed: 200,
isTotalWreck: false,
turnRadius: 30,
};
Intersection-typer
const foo: any = 5;
foo.toUpperCase();
foo.this.will.fail;
function meh(bar) {
bar.also.fails();
}
any
function throwError(message: string): never {
throw new Error(message);
};
never
function identity<T>(t: T): T {
return t;
}
Generics
type Nullable<T> = { [P in keyof T]: T[P] | null }
Oppgaver
github.com/bekk/typet-javascript-workshop
Typescript
By Erik Vesteraas
Typescript
- 950