Using Typescript Types

Using Typescript Types

Use the power Typescript types

Typescript comes with its types, and each one is part of typescript, not javascript.

Typescript will provide these types as part of our development process, notify the compiler of the data type used, and force us to implement them appropriately.


It helps set a variable or array with a set of values of different data types.

Tuples are very useful for not creating a dummy class or type to store two styles in a variable.

let codeRole: [number, string];

codeRole = [1504, "ADMIN"];

let sickTypePriority: [number, boolean, string][];

sickTypePriority = [
    [2033, true, "Cancer"],
    [2039, false, "Flu"]


The enum allows removing the magic numbers for a human-readable value using it as a type.

The enum is declared similar to an object with the enum keyword.

enum VatType {
    "NoTax" = 0.0,
    "SpainTax" = 21.0,
    "Private" = 12.0

We use enum as a type in the variables or props.

let payment: {
    amount: number;
    tax: VatType;
} = {
    amount: 1400,
    tax: VatType.Private


Any type is flexible to a specific type assignment, as a javascript, and loses all compiler and checks.

The variables of any type can store all kinds without a compiler error.

let colors: any;  

colors = 1;
colors = "hello"
colors = []
colors = true;

Union Types

The union types allow combining two or more variable types to use with the compiler check restriction.

For example, we want to store the security key, which can be a number or string.

We can use the union types in function parameters.

Let securityKey : string | number; 
securityKey = "DEFAULT TOKEN";
securityKey = 213235456;

function AddToken(token: number | string) {  

Literal Types

The literal types help when we know accepted values stored in a variable, similar to a union type.

We can use it to force specific values.

let currencyType: 'USD' | 'EUR' | 'DO'

currencyType = "DO";
currencyType = "EUR";

Type Aliases

Type aliases help to create your type using the type keyword.

Using the union type, you can combine all types instead create a dummy class.

type BankAccount = { name: string; amount: number };

class Bank {
    process(account: BankAccount) { = "Saving";
        account.amount = 1500;


The unknown type allows store any data but with restrictions on initialization.

Unknown doesn't allow us to assign his type to another data type; instead, we are sure of the conversion.

let token: unknown;
let key: string;

token = "asdasdas";
key = "hello world";

key = token;

error TS2322: Type 'unknown' is not assignable to type 'string.'

key = token;


Hopefully, that will give you a bit of help using the Typescript types. If you enjoyed this post, share it.

Photo by Deon Black on Unsplash