A short Introduction:
Welcome to the dynamic world of TypeScript—a powerful superset of JavaScript that enhances your coding experience with static typing and advanced features, offering robust type-checking capabilities, improved code maintainability, and seamless integration with popular frameworks like React in your MERN stack. In this blog, we'll explore the fundamentals of TypeScript, its benefits, and how it elevates your development skills for solving complex problems while contributing to open source projects.
You won't be missing the readability using typescript.
Most Used Types:
Boolean
String
number
Array
Object
void
undefined
touple
never
any
---
Example Declaring variables:
let name: String
// can also init this here which is not a good practice though
//as javascript knows that
let name : String = 'Ali';
Creating Functions:
function helper(isPaid : boolean){
if(isPaid === void 0) { isPaid = true; }
console.log(isPaid);
}
// here isPaid === void 0 check is this undefinded
// i.e void o === undefined
Return type of functions:
function helper(isPaid : boolean = false) : boolean{ if(isPaid === void 0) { isPaid = true; } console.log(isPaid); return isPaid; } // here isPaid: boolean = false; set defualt value as 'false'
Using 'never' keyword:
//In TypeScript, the never type is often used to indicate values that will // never occur or functions that will never return normally. //Example: function handleError(error : String){ throw new Error(error); }
keyword ' any '
// it's not a best practice to use any keyword.
// it's is used where you have no idea what type can be
//i.e it remove typesafety
let name : any
const handlefunc = (val : any ) : any => { return 2};
Aliases & type:
What are aliases these can be used to define type
type User = {
name : String,
age : number
}
function helper( user : User ){
console.log(user.name);
}
helper( "ali", 18);
// make sure to provide same values and types that are req for the func
Object Type:
Although you can say that before learning aliases one should learn object and know the above learning will help you a lot.
fucntion helper( { name : String , age : number }){
console.log( name );
}
// this is taking an object of the defined types
helper( " ali " , 18)
// what if we pass more than these values
helper( " ali ", 18 , false);
// yes this will still work but in case aliases it do give error
'readOnly' keyword:
type User = {
readonly id : number,
age : number;
}
let user : User = {
id : 1,
age : 20
}
// user.id = 2; // error
user.age = 12;
Optional type:
type User = {
readonly id : number,
age : number,
dead?: boolean // this is syntax might look wired
}
let user : User = {
id : 1,
age : 20
// using dead is optional here
}
// user.id = 2; // error
user.age = 12;
Addition of types:
type nametype = {
name : Stirng
}
type agetype = {
age : number
}
type user = nametype & agetype & {
readOnly id : number
}
Arrays in TS:
// these are two methods that are used and are equivalent
const arr_user : String[] = ['a','b','c'];
const arr_user1 : Array<String> = ['a','b','c'];
// readonlyarray
const arr_user2 : ReadonlyArray<String> = ['a','b','c'];
// arr_user2.push('aa') // give error
Union:
const name : String | number;
const arr_user : String[] | number[] = [1,2,3]
// can only by number type array or string type array
If want to define array containing differ types of values
const arr : (String | number )[] = [ 'a', 1]
const arr_user5 : Array<String | number> = ['a','b','c'];
touple:
These are fixed size arrays where the length of the array is already defined & type
const arr : [String, number] = ['a', 1];
// here we can't do this
const arr_user6 : [String, number] = ['a', 1, 3];
// also values can be changed
arr[0] = 'b' // but same type
Some fun facts about tuple:
const arr : [String, number] = ['a', 1];
arr.push(3); // still works
//methods like
arr.splice()
arr.pop()
arr.pop()
arr.unshift()
// can still alter the array length
Interface:
interface User = {
name : String,
age : number,
method() : String, // method that return string
setAge : () => String // method that return string
}
so, when ever interface is used the required fields should be provided
Example:
const user : User = {
name : 'ali',
age : 12,
method: ()=> { return 'String' }
setAge: ()=> { return 'String' }
}
Re-open Interface:
interface User = {
name : String,
age : number,
method() : String, // method that return string
setAge : () => String // method that return string
}
interface User = {
addfield ?: String // '?' is optional
}
// hance you have added one more value to the interface
Extends keyword:
interface room extends User {
addiontalfield: String
}
Conclusion: Mastering the Fundamentals of TypeScript
In this journey through the fundamentals of TypeScript, we've delved into the powerful features that make TypeScript a robust and expressive language for modern web development. From static typing and interfaces to advanced types and type guards, we've explored the tools that enhance code quality and catch errors at compile-time.