Using Typescript types

March 31, 2020

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

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

Tuples

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

tuples are very userfull to dont create a type or dummy class or type just for a store 2 types in a variable.

let codeRole: [number, string];

codeRole = [1504, "ADMIN"];

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

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

Enums

The enum allows removing the magic numbers for a human-readable value and can be used as a type.

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

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

The enums can be used as a type in the variables or props.

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

Any

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

The variables with any type can store all types without a compiler error.

let colors: any;  

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

Union Types

the union types allow to combine 2 or more types for our variable or paramenter with the compiler check restriction.

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

The union types can be used in function parameters.

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

function AddToken(token: number | string) {  
    console.log(token); 
}

Literal Types

The literal types can be used when we know accepted values that can be 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 are used to create your own 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) {
        account.name = "Saving";
        account.amount = 1500;
    }
}

unknow

the unknow type allow store any data but with the restriction when it is initialized.

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;