14 Data Types of Typescript you should know for beginners 👨🏻💻👩💻
image from kunal-chowdhury.com
If you see the long reading time for this article, don't worry 😉. I have written this awesome😎 article with many code examples😃 (with some nice Meme😂 as well); it's not just theory🔥.
So, buckle up🚀. We will begin our incredible journey🛣
First of all
These are all 14 Data types in Typescript that you should know tho✊
- Boolean
- Number
- String
- Array
- Tuple
- Enum
- Unkown
- Any
- Void
- Null / Undefined
- Never
- Object
- Type assertions
- Non-null assertion operator
type : boolean
The easiest one 😉
The most basic data type is the simple true/false value, which Typescript(or any else language) calls a Boolean.
To use boolean data types in Typescript, for declaring variables, use the Boolean
keyword ;
let isMarried: boolean = false ✅ 😊
let isMarried: Boolean = false ❌
note :
Boolean
with an upper case B is different fromboolean
with a lower case b.Boolean
is an object-type whereasboolean
is a primitive type. It’s a good practice to avoid❌ using theBoolean
type. 👍
type : number
All numbers in Typescript are either floating-point values or Big Integers. The floating-point numbers have the typenumber
while big integers get the type bigint
.
//Floating-numbers//
let decimal: number = 8; ✅
let hex: number = 0xf00d; ✅
let binary: number = 0b1010; ✅
let octal: number = 0o744; ✅
let decimal: Number = 7; ❌
// Upper case Number refers to
// the non-primitive boxed object.
// You should not use this Number type
// as much as possible in TypeScript.
//Big integers//
let big: bigint = 100n; ✅
note :
bigint
represent the whole numbers larger than (2^53 - 1). A Big integer literal has then
character at the end of an integer literal.
type : string
When you want to use textual data, string types are used and get denoted by the keyword string
. Like Javascript, Typescript also uses double-quotes (" ") and single quotes (' ') to surround the string value ;
let language: string = 'TypeScript';
// using single quote (' ')
let title: string = "not bad";
// using double quote (" ")
Since TypeScript version 1.4, TypeScript has included support for ES6 Template strings 🥳.
When you want to span a string to multiple lines and/or have to embed expressions (${expression})
, you can use templated strings. The templated strings are surrounded by a backquote/backtick (`) as shown in the below code snippets:
let car: string = "Tesla"; 😎
let carPrice: number = 40000; 🤑
let sentence: string = `I wanna buy ${car} soon,
the price is much affordable: ${carPrice}USD🔥`;
// output:
// I wanna buy Tesla soon, the price is
// much affordable: 40000USD🔥
type : [ Array ]
TypeScript supports arrays, similar to JavaScript😃. There are two✌️ ways to declare an array:
1) [ Using square brackets ]
This method is similar to how you would declare arrays in JavaScript.
let fruits: string[] = ['Apple', 'Orange', 'Banana']; ✅
let list: number[] = [1,2,4]; ✅
note :
type[ ]
is to denote an array of that element type
2. Using a generic array type, Array<elementType>
let fruits: Array<string> = ['Apple', 'Orange', 'Banana']; ✅
let list: Array<number> = [1,2,3] ✅
Both methods produce the same output.✌️
Arrays can contain elements of any data type, numbers, strings, or even objects.
Arrays can be declared and initialized separately.
let fruits: Array<string>;
fruits = ['Apple', 'Orange', 'Banana'];
let ids: Array<number>;
ids = [23, 34, 100, 124, 44];
An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below.
let teslaModel: (string | number)[] = ['S', 3, 'X', 'Y', 'C', 'A', 'R', 'S']; 🔥
// or
let teslaModel: Array<string | number> = ['S', 3, 'X', 'Y', 'C', 'A', 'R', 'S'];
Array Methods
The following example demonstrates some of the array methods and many more😃. Same as Javascript tho😎
var fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
fruits.sort();
console.log(fruits);
//output: [ 'Apple', 'Banana', 'Orange' ]
console.log(fruits.pop());
//output: Orange
fruits.push('Papaya');
console.log(fruits);
//output: ['Apple', 'Banana', 'Papaya']
fruits = fruits.concat(['Durian', 'Mango']);
console.log(fruits);
//output: ['Apple', 'Banana', 'Papaya', 'Durian', 'Mango']
console.log(fruits.indexOf('Durian'));
//output: 3
type : tuple
A tuple is a data type that allows you to create an array where the type of a fixed number of elements are known but need not be the same.Yadayada😑, give me some code snippet.
Consider this ;
var playerId: number = 5;
var playerName: string = "John";
// Tuple type variable
var player: [number, string] = [5, "John"];
The same thing can be achieved by using a single tuple type variable. The player is the tuple type variable with two values of number and string type. Thus, removing the need to declare two different variables.😃
You can declare an array of tuple also.🔥
var player: [number, string][];
employee = [[1, "Raj"], [2, "Gates"], [3, "Zack"]];
Watch Out‼️
// Declare a tuple type
let y: [string, number];
// Initialize it
y = ["hello", 7]; // OK ✅
// Initialize it incorrectly
y= [7, "hello"]; // Error❌
Accessing an element outside the set of known indices fails with an error:
y[5] = "awesome";
// Tuple type '[string, number]' of length '2' has
// no element at index '5'.
note :A tuple works like an array with some additional considerations:
- The number of elements in the tuple is fixed.
- The types of elements are known, and need not be the same.
type : enum
An enum is a group of named constant values. Enum stands for enumerated type.
To define an enum, you follow these steps:
- First, use the enum keyword followed by the name of the enum.
- Then, define constant values for the enum.
For example, you can use an enum for the approval status:
enum ApprovalStatus {
draft,
submitted,
approved,
rejected
};
Then, you can use the ApprovalStatus
enum like this:
const request = {
id: 5,
status: ApprovalStatus.submited,
description: 'Content is submitted'
};
if(request.status === ApprovalStatus.submitted) {
// send an email
console.log('Send email to the Subscriber...');
}
or
enum PrintMedia {
Newspaper , // 0
Newsletter, // 1
Magazine, // 2
Book // 3
}
function getMedia(mediaName: string): PrintMedia {
if ( mediaName === 'Smashing' || mediaName === 'Inc') {
return PrintMedia.Magazine;
}
}
let mediaType: PrintMedia = getMedia('Inc'); // returns Magazine
By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one of its members.
For example, we can start at 1 instead of 0:😉
enum Color {
Red = 1,
Green,
Blue,
}
let c: Color = Color.Blue;
Or, even manually set all the values in the enum:😃
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
let c: Color = Color.Blue;
cool right 🔥
type : unknown
We may need to describe the type of variables that we do not know🧐 when we are writing an application. These values may come from dynamic content – e.g. from the user👨 – or we may want to intentionally accept all values in our API.
In these cases, we want to provide a type that tells🗣 the compiler and future readers that this variable could be anything, so we give it the unknown
type.
let dontKnow: unknown = 3
dontKnow = 'string instead'
// Ok , definitely boolean 😆
dontKnow = true
awesome🚀
type : any
Sometimes, you may need to store📥 a value in a variable🏠. But you don’t know its type at the time of writing the program. And the unknown value may come from a third party API or user input.
In this case, you want to opt-out of the type checking and allow the value to pass through the compile-time check.
To do so, you use the any
type. The any
type allows you to assign a value of any type to a variable😃:
let looselyResult: any = 4;
// OK, ifItExists might exist at runtime
looselyResult.ifItExists(); ✅
// OK, toFixed exists (but the compiler doesn't check)
looselyResult.toAdd(); ✅
let strictlyResult: unknown = 4;
strictlyResult.toFixed(); ❌
Unlike unknown
, variables of type any
allow you to access arbitrary properties, even ones that don’t exist😃. These properties include functions and TypeScript will not check their existence or type.
After all, remember that all the convenience of any comes at the cost of losing type safety. Type safety is one of the main motivations for using TypeScript😁 and you should try to avoid using any
when not necessary.😉
type : void
Similar to languages like Java, void
is used where there is no data. For example, if a function does not return any value, then you can specify void as return type😉.
function sayHello(): void {
console.log('Hello!')
}
let speech: void = sayHello();
console.log(speech); //Output: undefined
There is no meaning to assign void
to a variable, as only null or undefined is assignable to void😎.
let nothing: void = undefined; ✅
let nothing: void = null; ✅
let num: void = 1; // Error ❌
type : null
and undefined
In TypeScript, both undefined and null actually have their types named undefined
and null
respectively. Much like void
, they’re not extremely useful on their own😂:
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
type : never
TypeScript introduced a new type never
, which indicates the values that will never occur.
The neve
r type is used when you are sure that something is never going to occur. For example, you write a function that will not return to its endpoint or always throws an exception.
function throwError(errorMsg: string): never {
throw new Error(errorMsg);
}
function keepProcessing(): never {
while (true) {
console.log('I always does something and never ends.') 😆
}
}
In the above example, the throwError()
function throws an error, and keepProcessing()
function is always executing and never reaches an endpoint because the while loop never ends😂. Thus, never type is used to indicate the value that will never occur or return from a function.
Difference between never and void
Yeah I know, you might question this stuff in your head(same as me tho😆) Consider this ;
let something: void = null;
let nothing: never = null; // Error: Type 'null' is not assignable to type 'never'
The void
type can have undefined or null as a value whereas never
cannot have any value.
In TypeScript, a function that does not return a value actually returns undefined
. Consider the following example;
function sayHello(): void {
console.log('Hello!')
}
let speech: void = sayHello();
console.log(speech); // undefined
As you can see in the above example👆,speech is undefined, because the sayHello
function internally returns undefined
even if the return type is void
. If you use never
type, speech:never
will give a compile-time error, as void
is not assignable to never
.
Fuuhh understood ??? 🚀
type : object
object
is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined.
With object type, APIs like Object.create
can be better represented. For example:
declare function create(o: object | null): void;
create({ prop: 0 }); ✅
create(null); ✅
create(42); ❌
create("string"); ❌
create(false); ❌
create(undefined); ❌
Open this Playground for better Error explanations
type : Type assertions
Sometimes you’ll end up in a situation where you’ll know more about value than TypeScript does😎. Usually, this will happen when you know the type of some entity could be more specific than its current type.
Type assertions are a way to tell the compiler “trust me, I know what I’m doing.”
😂. TypeScript assumes that you, the programmer, have performed any special checks that you need.
There are two✌️ ways to do type assertion
in TypeScript:
1) Using the angular bracket <>
syntax
let code: any = 357;
let playerCode = <number> code;
2) Using as
keyword
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
The last one 😃
type : Non-null assertion operator
TL;DR: Adding an exclamation mark !
after a variable will ignore undefined
or null
types.🤩
It's a new Typescript 2.0 feature and you can read about it in the what's new page
By default, null
and undefined
are assignable to all types in TypeScript e.g.
let meh: number = 345;
meh = null; ✅
meh = undefined; ✅
In strict null checking mode, null and undefined are different:
let meh = undefined;
meh = null; // NOT Okay ❌
Let's say we have a Member
interface:
interface Member {
name: string,
age?: number 👈
}
Not every Member
will provide their age, so age is an optional property, meaning the value of age may or may not be undefined😎.
undefined
is the root of all evil😆. It often leads to runtime errors. It is easy to write code that will throw Error
at runtime:
getMember()
.then(member: Member => {
const stringifyAge = member.age.toString() ❌
// Cannot read property 'toString' of undefined
})
But in strict null checking mode, this error will be caught at compile time:
getMember()
.then(member: Member => {
const stringifyAge = member.age.toString() ✅
// Object is possibly 'undefined'
})
note : Like all
assertions
, you are telling🗣 the compiler to trust you😎. The compiler will not complain even if the code doesn't actually always assign the property.
Read
Muahahah😆 If you still don't understand what it is😅
Finish 🏁
Wuhuuu🥳
Thanks for finishing it 🙌
You're Awesome 😎
Bookmark and Share it 🤟
Resources ;
note : If you find any error, please ping me on the comment section👌