TypeScript Fundamentals in One Place
1. Introduction
Programming language divide into two classes :
Statically typed
Dynamically typed
in Statically-typed
languages (C, Java, C#, … ), the kind of variable is about on the compile-time and can’t change later.
in Dynamically-typed
languages (PHP, JavaScript, Python, … ), the kind of variable is set on the run-time and may change later.
TypeScript
is a programming language construct on high of JavaScript
( primarily JavaScript with static typing and a few extra options ) , so earlier than we star just be sure you are conversant in this ideas in javascript:
- Variables
- Arrays
- Objects
- Features
- Arrow Features
- Destructuring
- …
2. Constructed-in Sorts
as we all know JavaScript
has built-in sorts like :
- quantity
- string
- boolean
- array
- object
- undefined
- null
So TypeScript
prolong this record and introduce some new built-in sorts equivalent to :
- any
- unknown
- by no means
- enum
- tuple
1- The Any Kind :
once you declare a variable and do not initialize it , the typescript compiler will assume that variable is kind of any
which implies you possibly can assign any kind of information into it , right here is an instance :
let anyType; // let anyType: any
anyType = 12;
console.log(typeof anyType); // output: quantity
anyType = "Random string";
console.log(typeof anyType); // output: string
Be aware :
To declare variables, capabilities
you simply must observe this syntax :
let numberType: quantity = 12;
let numberType: string = 12;
operate taxe(revenue: quantity): quantity {
return revenue * 0.2;
}
2- Arrays :
let numbers = [1, 2, 3]; // let numbers: quantity[] = [1, 2, 3]
let anyTypes = []; // let anyTypes: any[]
anyType[0] = 100;
anyType[0] = "r_string";
let names = ["ahmed", "zineddine"]; // let names: string[] = ["ahmed", "zineddine"]
3- Tuples :
A tuple is a typed array with a pre-defined size and kinds for every index.
let worker: [number, string] = [1, "Steve"];
4- Enums :
// const small = 1;
// const medium = 1;
// const massive = 1;
const enum Dimension {
Small = 1,
medium,
massive,
}
let mySize: Dimension = Dimension.Small;
console.log(mySize); // output : 1
4- Objects :
/*
let worker: {
id:quantity,
title:string
} = {
id:1,
title:'zineddine'
}
*/
let worker = {
id: 1,
title: "zineddine",
};
let person: {
readonly id: quantity;
title: string;
pseudo?: string;
retire: (date: Date) => void; // operate declaration
} = {
id: 1,
title: "zineddine",
retire: (date: Date) => {
console.log(date);
},
};
person.id = 10; // Can't assign to 'id' as a result of it's a read-only property
5- Kind Aliases :
kind Person = {
readonly id: quantity;
title: string;
pseudo?: string;
retire: (date: Date) => void; // operate declaration
};
let person: Person = {
id: 1,
title: "zineddine",
retire: (date: Date) => {
console.log(date);
},
};
6- Union Sorts :
operate kgToLbs(kg: quantity | string): quantity {
// Narrowing
if (typeof kg === "string") {
return parseFloat(kg) * 2.2046;
}
return kg * 2.2046;
}
7- Intersection Sorts :
// make no sense proper ?
let weight: quantity & string;
// let see a sensible instance
kind draggable = {
drag: () => void;
};
kind resizable = {
resize: () => void;
};
let UIWidget: draggable & resizable;
UIWidget = {
drag: () => {},
resize: () => {},
};
8- Literal Sorts :
// let amount: 5 | 100;
kind Amount = 50 | 100;
let amount: Amount;
amount = 5; // Kind '5' is just not assignable to kind 'Amount'
kind Metric = "m" | "cm" | "mm";
9- Nullable Sorts :
operate greeting(title: string | null | undefined) {
if (title) {
return `Hi there, ${title}`;
}
return "Hi there, World";
}
greeting("John");
greeting(null);
greeting(undefined);
10- Elective Chaining :
kind Person = {
id: quantity;
birthday?: Date;
};
operate getUser(id: quantity): Person | null | undefined {
if (id === 1) {
return {
id,
birthday: new Date("2000-01-01"),
};
}
return null;
}
getUser(0); // output null
getUser(1); // output { id: 1, birthday: Date }
// non-compulsory property entry operator
getUser(1)?.birthday?.getFullYear(); // output 2000
// non-compulsory component entry operator
let workers: string[] | null = null;
workers?.[0];
// non-compulsory operate name operator
let log: any = null;
log?.("hey"); // return undefined
11- Nullish Coalescing Operator :
let velocity: quantity | null = null;
let journey = ;
12- Kind Assertions :
let cellphone = doc.getElementById("cellphone");
cellphone.worth; // Property 'worth' doesn't exist on kind 'HTMLElement'
// let e mail = <HTMLInputElement> doc.getElementById('e mail');
let e mail = doc.getElementById("e mail") as HTMLInputElement;
e mail.worth;
13- The Unknown Kind :
operate render(doc: any) {
// no compile error , however runtime error
doc.whatEver();
}
operate render(doc: unknown) {
/*
compile error, now the compîler forces us to examine the kind of the argument earlier than utilizing it
*/
doc.whatEver();
if (doc instanceof String) {
doc.toLocaleLowerCase();
}
}
13- The By no means Kind :
operate reject(message: string): by no means {
throw new Error(message);
}
operate processEvent(): by no means {
whereas (true) {
// ...
}
}
processEvent();
/*
=> this code won't ever be executed , however the compiler do not inform us , so we've to make use of the `by no means` kind.
=> now the compiler will inform us that the operate won't ever return : Unreachable code detected.
*/
console.log("Hi there World!");
That’s it for the primary chapter !
Github hyperlink : TypeScript-Fundamentals-in-One-Place