4IT580: Docs
4IT580 WebGitLab

TypeScript cheatsheet

TypeScript builds on top of JavaScript. First, you write the TypeScript code. Then, you compile the TypeScript code into plain JavaScript code using a TypeScript compiler.

Once you have the plain JavaScript code, you can deploy it to any environment that JavaScript runs.

Why TypeScript?

Primitives

string

number

boolean

Literal value

Structural types

Specific object with properties

Type aliases

Array

Using primitives

Using structural types

Tuple

Enum

DO NOT USE ! There are many problems with TypeScript enums. It is a crime against humanity to use in TypeScript.

Instead use string union:

For more info see this video.

Optional and nullable

Optional value

This is usefull for optional properties.

Nullable

This is usefull to express that value is specail state.

Functions

Parameters

ES6 arrow function

Return type

Optional parameters

Default parameters

Rest parameter

Structural typing

Sometimes called "duck typing" (If it walks like a duck and it quacks like a duck, then it must be a duck).

Comparing types is done by comparing the structures, not the names of types.

If contains the same properties as , it is safe to pass it as an argument of .

You can read about structural type system in official docs.

Interfaces

Basic

Extending interface

Shall I use or for objects?

Watch this video for explanation. TL;DR: use .

Unions and Intersection

Union - OR

String literal

Intersection - AND

Generics

Basic

Constraints

Miscellaneous

Type

When you want to assign whatever type, you can use . Good practice is to NOT use this type, since you lose the typesafety.

Type

This type is usually used with casting or as a default type in generics.

Type

Casting type

Please try to avoid type casting. In some advanced use-cases there is no way around it, but it should be avoided as much as possible.

Inference

Most of the type, when you create a new variable you dont have to specify the type, since TypeScript can infer it for you. It is always good to check, if the inferred type is correct, in your IDE.

Utilities

Pick

more props

Omit

Partial

Required

Record

ReturnType

React example

Links