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;
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";
Boolean
This is one of the basic types which contains boolean
value true
or false
const loading: boolean = true|false;
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"]
Second way -
const numbers: Array<number> = [1, 2, 3]
const products: Array<string> = ["bag", "laptop", "mobile"]
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 }];
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
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
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)
Great! Very informative and thanks for sharing your opinion.