cheatsheets/typescript.md

289 lines
3.9 KiB
Markdown
Raw Permalink Normal View History

2017-02-20 09:25:13 +00:00
---
title: TypeScript
category: JavaScript libraries
---
2023-03-13 12:02:33 +00:00
### About
2017-02-20 09:25:13 +00:00
TypeScript is just like ES2015 with type-checking. All ES2015 (classes, etc) should work.
2023-03-13 12:02:33 +00:00
### Basic types
2017-02-20 09:25:13 +00:00
```ts
any
void
boolean
number
string
null
undefined
2022-10-27 02:23:21 +00:00
bigint
symbol
2017-02-20 09:25:13 +00:00
string[] /* or Array<string> */
[string, number] /* tuple */
string | null | undefined /* union */
never /* unreachable */
2022-10-27 02:23:21 +00:00
unknown
2017-02-20 09:25:13 +00:00
```
```ts
2022-10-27 02:23:21 +00:00
enum Color {
Red,
Green,
Blue = 4
};
2017-02-20 09:25:13 +00:00
let c: Color = Color.Green
```
2023-03-13 12:02:33 +00:00
### Declarations
2017-02-20 09:25:13 +00:00
```ts
let isDone: boolean
let isDone: boolean = false
```
```ts
function add (a: number, b: number): number {
return a + b
}
// Return type is optional
function add (a: number, b: number) { ... }
```
## Type assertions
2018-07-31 15:24:26 +00:00
#### Variables
2017-02-20 09:25:13 +00:00
```ts
let len: number = (input as string).length
let len: number = (<string> input).length /* not allowed in JSX */
```
2018-07-31 15:24:26 +00:00
#### Functions
```ts
function object(this: {a: number, b: number}, a: number, b: number) {
this.a = a;
this.b = b;
return this;
}
// this is used only for type declaration
let a = object(1,2);
// a has type {a: number, b: number}
```
2017-02-20 09:25:13 +00:00
## Interfaces
### Inline
```ts
function printLabel (options: { label: string }) {
console.log(options.label)
}
// Note the semicolon
function getUser (): { name: string; age?: number } {
}
```
### Explicit
```ts
interface LabelOptions {
label: string
}
function printLabel(options: LabelOptions) { ... }
```
### Optional properties
```ts
interface User {
2022-10-27 02:23:21 +00:00
name: string;
age?: number;
2017-02-20 09:25:13 +00:00
}
```
### Read only
```ts
interface User {
readonly name: string
}
```
### Dynamic keys
```ts
{
[key: string]: Object[]
}
```
## Type aliases
2023-03-13 12:02:33 +00:00
### Type aliases
2017-02-20 09:25:13 +00:00
```ts
type Name = string | string[]
```
2022-10-27 02:23:21 +00:00
### Intersection
```ts
interface Colorful { ... }
interface Circle { ... }
type ColorfulCircle = Colorful & Circle;
```
2017-02-20 09:25:13 +00:00
## Function types
```ts
interface User { ... }
function getUser(callback: (user: User) => any) { callback({...}) }
getUser(function (user: User) { ... })
```
## Classes
```ts
class Point {
x: number
y: number
static instances = 0
constructor(x: number, y: number) {
this.x = x
this.y = y
}
}
```
2018-07-31 15:24:26 +00:00
#### Inheritance
```ts
class Point {...}
class Point3D extends Point {...}
interface Colored {...}
class Pixel extends Point implements Colored {...}
```
#### Short fields initialisation
```ts
class Point {
static instances = 0;
constructor(
public x: number,
public y: number,
){}
}
```
#### Fields which do not require initialisation
```ts
class Point {
public someUselessValue!: number;
...
}
```
2017-02-20 09:25:13 +00:00
## Generics
```ts
class Greeter<T> {
greeting: T
constructor(message: T) {
this.greeting = message
}
}
let greeter = new Greeter<string>('Hello, world')
```
## Modules
2018-07-31 15:24:26 +00:00
```ts
2017-02-20 09:25:13 +00:00
export interface User { ... }
```
2018-07-31 15:24:26 +00:00
## Type extraction
```ts
interface Building {
room: {
2022-10-27 02:23:21 +00:00
door: string;
walls: string[];
2018-07-31 15:24:26 +00:00
};
}
type Walls = Building['room']['walls']; // string[]
```
2022-10-27 02:23:21 +00:00
## Keyof Type Operator
```ts
type Point = { x: number; y: number };
type P = keyof Point; // x | y
```
## Conditional Types
2022-10-27 02:23:21 +00:00
```ts
// SomeType extends OtherType ? TrueType : FalseType;
type ToArray<T> = T extends any ? T[] : never;
type StrArrOrNumArr = ToArray<string | number>; // string[] | number[]
```
### Inferring
```ts
type GetReturnType<T> = T extends (...args: unknown[]) => infer R
? R
: never;
type Num = GetReturnType<() => number>; // number
```
```ts
type First<T extends Array<any>> = T extends [infer F, ...infer Rest] ? F : never;
type Str = First<['hello', 1, false]>; // 'hello'
```
## Literal Type
```ts
const point = { x: 4, y: 2 }; // { x: number, y: number }
const literalPoint = { x: 4, y: 2 } as const; // { readonly x: 4, readonly y: 2 };
```
## Template Literal Types
```ts
type SpaceChar = ' ' | '\n' | '\t';
type TrimLeft<S extends string> = S extends `${SpaceChar}${infer Rest}` ? TrimLeft<Rest> : S;
type Str = TrimLeft<' hello'>; // 'hello'
```