Basic Types in Typescript

A SHORT NOTE ON TYPESCRIPT TYPES – BOOLEAN, NUMBER, STRING, ARRAY, TUPLE, ENUM, ANY, VOID, NULL, UNDEFINED, NEVER, INTERFACES

Variables hold the simplest unit of data. Variables in Typescript can be of many types. Typescript data types can be assumed as Javascript basic types such as strings, numbers, arrays, objects etc with some addons which are either completely ignored in Javascript during compile time or transformed into a Javascript native structures during compilation.

If you are not sure on how to install or use Typescript then please refer the article here

Before we dive deep into its essential that we understand two basic terminologies with types in Typescript


Type Inference

Typescript has the ability to automatically infer variable types based on the value given to the variable.

// Without Inference
let fruit: string = 'mango';

In the above example from the value its understood that the type is string. We could save typing here as Typescript can infer the type from the value

// With Inference
let fruit = 'mango';

Typescript automatically tags the variable as a string type and you get all the benefits of traditional variable declaration. This becomes very handy when a type is large interfaces and typing that would be a pain.

// This will have any type
let fruit;

When Typescript cannot infer types, then any is infered. This will cause an error when noImplicitAny is enabled in tsconfig.json.


Type Assertion

It could be handy when we can force Typescript compiler to consider the variable as one type when it cannot be inferred. The best example would be the data from a api endpoint. Typescript cannot definitely understand the type of data that is returned by a API response.

const url = 'http://example.com/api/v1/todo';
const headers = {
	"Content-Type": "application/json"
};

try {
	const client = await fetch(url, {
		headers: headers, method: 'GET'
	});

	if (!client || !(client.status === 200 || client.status === 201)) {
		throw new Error(await client.text());
	}

	const result = await client.json() as string;
} catch (e) {
 	console.error(e);
}

In the above example result is asserted the value of string.

Type assertion can be declared using

const someValue: any = 'this is a string';
const fruit = <string> someValue;

In the about example fruit is asserted as a string type.


Strings

Fundemental part of Typescript is the string type which holds textual data. Typescript strings are similar to strings in Javascript and can be created with "', or backtick/backquote (`)

let language:  = 'javascript';
language = "typescript";

The resulting Javascript code is

"use strict";
const message = 'hello world';

Number

All numbers which includes decimal, binary, hexadecimal, octal and floating points are belong to this type in Typescript.

Note: All numbers in Typescript are floating point values

let decimal: number = 2;
let float: number = 2.3333;
let hex: number = 0xf0230d;
let binary: number = 0b1111010;
let octal: number = 0o73244;

The resulting Javascript code is

"use strict";
let decimal = 2;
let float = 2.3333;
let hex = 0xf0230d;
let binary = 0b1111010;
let octal = 0o73244;

Boolean

Boolean data type is simply true/false values

let done: boolean = true
let notDone: boolean = false

The resulting Javascript code is

"use strict";
let done = true;
let notDone = false;

Array

Typescript array looks like a Javascript array with types. Array can be written in two ways

let list: number[] = [1, 2, 3];
let nums: Array<number> = [4, 5, 6];

The resulting Javascript code is

"use strict";
let list = [1, 2, 3];
let nums = [4, 5, 6];

Tuple

Developers from a python background will definitely understand this data structure initially as python extensively uses tuples. Tuples are similar to Arrays but allow us to express only a fixed number of elements. Tuples need not have the same data type as an array.

let x: [string, number];

x = ['string', 1] // Goes very well
x = [1, 1]; //Error

The resulting Javascript code is simply an array

"use strict";
let x;
x = ['string', 1]; // Goes very well

Enums:

Java developers out there would love this type and they would be happy to see this type in Typescript when onboarded to it.

Enums are used when a variable can take only a small set of possible values. Enum defaults to a number starting from 0 if no value is specified and results in the value specified when any value is given.

enum fruits {
    mango,
    apple,
    pineapple
}

console.log(fruits.apple) // Results in 1

In the above example mango is assigned a value 0, apple with 1 and so on. This is the default asignment when no value to enum is specified.

enum fruits {
    mango,
    apple,
    pineapple
}

enum languages {
    java = 'java',
    javascript = 'javascript',
    typescript = 'typescript',
}

console.log(languages.java) // Results in java

Here languages have a definite value and when used results in the same value

The resulting Javascript code is initially a confusing one but its just a Javascript object with the same name assigned with either the default value or the assigned value.

"use strict";
var fruits;
(function (fruits) {
    fruits[fruits["mango"] = 0] = "mango";
    fruits[fruits["apple"] = 1] = "apple";
    fruits[fruits["pineapple"] = 2] = "pineapple";
})(fruits || (fruits = {}));
var languages;
(function (languages) {
    languages["java"] = "java";
    languages["javascript"] = "javascript";
    languages["typescript"] = "typescript";
})(languages || (languages = {}));
console.log(languages.java); // Results in 1

Note that fruits can also be index using index as fruits[0] which results in mango

enum fruits {
    mango,
    apple,
    pineapple
}

console.log(fruits) // Results in {0: "mango", 1: "apple", 2: "pineapple", mango: 0, apple: 1, pineapple: 2}

console.log(fruits[0]) // Results in mango

Any

Any as the name suggest can take any type of variable we visited so far. This is applicable when we want to describe the data for which we don’t know the type.

Any is a good type when we are working with existing javascript code, but should be avoided at all cost when writing a Typescript application. Working without type definition spoils the fun that Typescript brings along with it.

let unSureType: any = 4

The resulting Javaascript code is

"use strict";
let unSureType = 4;

Void

Void is just a opposite of any type where there is a absence of any type at all. This is commonly used when working with functions which returns no value.

let sum = (a: number, b: number) : void => {
    console.log(a + b)
}

The above function doesn’t return anything and hence the void. The below program will result in a error as it returns a number.

let sum = (a: number, b: number) : void => {
    return a + b // Error here
}

The resulting Javascript code is

"use strict";
let sum = (a, b) => {
    console.log(a + b);
};

Undefined and Null

Both undefined and null has there own types in Typescript. Like void they are not so useful when used on their own.

let val: undefined = undefined
let i: null = null

i = undefined // They are not inter assinable and this will result in a error

The resulting Javascript code is

"use strict";
let val = undefined;
let i = null;

Interfaces

Interfaces help in type checking for Objects and Classes. These are sometimes called duck typing or structural typing.

interface define {
    a: number;
    b: number;
    c: string;
}

class A implements define {
    a = 2;
    b = 2;
    c = 'some value';
} // No error

const obj: define = {
    a: 2,
    b: 3,
    c: ''
} // No error

const err: define = {
    a: 2
} // Will result in a error as c is not defined

the resulting Javascript code is

"use strict";
class A {
    constructor() {
        this.a = 2;
        this.b = 2;
        this.c = 'some value';
    }
} // No error
const obj = {
    a: 2,
    b: 3,
    c: ''
}; // No error
const err = {
    a: 2
}; // Will result in a error as c is not defined

Note that the interface is completely ignored in Javascript. Interfaces add value only during developmental and Compile phase and are completely ignored during run time.

Interfaces are highly useful when defining the structure for the data received through APIs

Leave a Comment