Extend types

Mateusz -

In JavaScript we have two categories of types.

Primitive types

boolean
number
string
symbol
bigInt
null
undefined

Complex types

object
array

TypeScript allows us to use kind new of types.

Enum

To put it simply it is a collection of named values (See Enums in JavaScript). In TypeScript enums are by default numbers starting from 0.

//
enum Suit { Spades, Hearts, Diamonds }

const suit: Suit = Suit.Spades //0
//

We can also define enums in the normal way, with key and values.

//
enum UserRole = { Admin = 'admin', User = 'user' };

const userRole = UserRole.Admin //admin
//

Tuple

It represents an array with defined number of elements and their types.

//
const tuple1: [number, string] = [1, ‘John’];
const tuple2: [firstName: string, age: number, value: number]
//

Union

When the type specified more than one data type.

//
let uniqID: (string | number);
code = 123;   // Good
code = 'e12030'; // Good
code = false; // Error
//

Void

Means “no value”. We can use it for example for functions that will return nothing.

//
function helloWorld(): void { 
    console.log('Hello World!')
}
//

Object

It is mainly used for other types to inherit from it.

Never

A special type, describes a value that will never occur (for example when you want to throw a new Error function).

//
function throwError(error: string): never { 
  throw new Error(error); 
}
//

Any

Means any type. Not recommend to use.

Unknown

Represents a type that is unknown. It is safer than any type because we cannot use this as often as any.