DEV Community

Cover image for TypeScript Basics
Suresh Pal Pranta
Suresh Pal Pranta

Posted on • Updated on

TypeScript Basics

TypeScript vs JavaScript

TypeScript is a superset of JavaScript. That means TypeScript has some extra features to JavaScript. In JavaScript, we don't need to define the type but in TypeScript, we have strictly followed the type. As a result, the chance of bugs will be lower.

Basic Types

Some common types are - number, string, boolean, undefined, null, unknown, any.

Number
In TypeScript, a variable that will store a decimal number the type of the variable should be defined as type number. While big integer gets the type bigint

const total: number = 1000;
const discount: number = 1000*0.1;
const max: bigint = 10n ** 9n;
Enter fullscreen mode Exit fullscreen mode

String
In TypeScript a variable that will store textual data, the type of the variable should be defined as type string

const name: string = "Pranta";
const position: string = "Frontend Developer";
Enter fullscreen mode Exit fullscreen mode

Boolean
This is one of the basic types which contains boolean value true or false

const loading: boolean = true|false;
Enter fullscreen mode Exit fullscreen mode

Array
We can define a type of array in three ways. The First two ways have explicitly defined the types. The third way simplifies the task by using an interface or type

First way -
const numbers: number[] = [1, 2, 3]
const products: string[] = ["bag", "laptop", "mobile"]
Enter fullscreen mode Exit fullscreen mode
Second way -
const numbers: Array<number> = [1, 2, 3]
const products: Array<string> = ["bag", "laptop", "mobile"]
Enter fullscreen mode Exit fullscreen mode

If we have an array of objects then we can use the type keyword or define an interface specifying the type of all properties in an object. Best way to use interface.

const IProducts {
   name: string;
   price: number;
}
const products: IProducts[] =[{ name: "Mobile", price: 10000}, { name: "Mobile", price: 10000 }];

Enter fullscreen mode Exit fullscreen mode

Any
The any type is rarely used. It helps to work with the existing JavaScript code. When all the data types are not known then we can assume it as any type.

const looselyTypedVariable: any = {};
console.log(looselyTypedVariable.name); //don't give any error
Enter fullscreen mode Exit fullscreen mode

But, there are some drawbacks to using any type. With any type TypeScript will not give any error whether we are accessing a property that doesn't exist in that object.

const strictlyTypedVariable: {name: string} = {name:"Pranta"};
console.log(strictlyTypedVariable.age); //show error
Enter fullscreen mode Exit fullscreen mode

Without using any we can use unknown type as well which is more meaningful. We should try to avoid using any when not necessary as it doesn't ensure the type safety.

Top comments (1)

Collapse
 
pranta07 profile image
Suresh Pal Pranta

Great! Very informative and thanks for sharing your opinion.