function add(a, b) {
return a + b;
}
function add(a: number, b: number): number {
return a + b;
}
TypeError: Cannot read property 'name' of undefined
TypeError: undefined is not a function
Autocomplete
Faster feedback loops
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 = {};
const myArray: number[] = [1, 2, 3];
const myTuple: [number, number] = [800, 600];
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;
}
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
}
}
enum Ternary {
FALSE,
TRUE,
MAYBE
}
enum Ternary {
FALSE = "FALSE",
TRUE = "TRUE",
MAYBE = "MAYBE"
}
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,
};
const foo: any = 5;
foo.toUpperCase();
foo.this.will.fail;
function meh(bar) {
bar.also.fails();
}
function throwError(message: string): never {
throw new Error(message);
};
function identity<T>(t: T): T {
return t;
}
type Nullable<T> = { [P in keyof T]: T[P] | null }
github.com/bekk/typet-javascript-workshop