-
Notifications
You must be signed in to change notification settings - Fork 5
TypeScript
Manujaya edited this page Jul 20, 2021
·
11 revisions
Assigning Variables
//Number
let x = 42;
let exampleNumber:number = 66;
//String
let exampleName: string = "Person1";
//Boolean
let exampleBoolean: boolean = false;
//Date
let exampleDate: Date = new Date(2021, 7, 17);
//Any
let exampleAny: any = "Can be anything";
//Array
let exampleArray1: string[] = ['index1', 'index2'];
let exampleArray2: Array<number> = [1,3];
let exampleArray3: number[] = [2,4];
//Enum
enum color{
RED,
GREEN,
BLUE,
}
let exampleEnum: color = color.GREEN;
console.log('exampleEnum :: ${typeof exampleEnum}');
//Null
let exampleNull: number = null;
//Tuple
//Similar to an array but different indexes have different types
let exampleTuple: [string, number];
Assigning Constant
//const can be used instead of let in above types
const exampleConstNum: number = 99;
const exampleConstString: string = "Value";
Void Function
function exampleVoid(msg: string): void {
console.exampleVoid(msg);
}
Example class:
class OrderLogic {
constructor(public order: IOrder) { }
getOrderTotal(): number {
let sum: number = 0;
for (let orderDetail of
this.order.orderDetails)
{
sum += orderDetail.price;
}
return sum;
}
}
npm install TypeScript
// @ts-nocheck
// @ts-check
// @ts-ignore
// @ts-expect-error
let a;
let b = 1;
// assign a value only if current value is truthy
a &&= 'default'; // a is still undefined
b &&= 5; // b is now 5
let a;
let b = 1;
// assign a value only if current value is false
a ||= 'default'; // a is 'default' now
b ||= 5; // b is still 1
let a;
let b = 0;
// assign a value only if current value is null or undefined
a ??= 'default'; // a is now 'default'
b ??= 5; // b is still 0