TypeScript
(PDF)
Posted February 9th, 2024
TypeScript is typed javascript that compiles to javascript
It reduces errors in javascript.
These are basic takeaways from reading about typescript
So typescript is compiled javascript with strict typing. 1) Install typescript npm i -g typescript 2) Check version tsc -v 3) Compile stuff in .ts files to .js files tsc -w 4) Defining variables let varname: type = default_value; types can be string, number, bigint, bool, null, undefined, symbol wrappers String,Number,BigInt, Boolean, Symbol union type: example : let foo: string|number=5; "any" type - not recommended - reverts to straight javascript const foo = document.querySelector('a')!; ! - indicates - non-null assertion to inform compiler type casting: const foo = document.getElementById('foobar') as HTMLFormElement; let flavors: 'chocolate'|'strawberry'|'blueberry'; 5) reference types - arrays, objects, functions a) arrays let myarray: number[] = [1,2,4,5]; let myarray: (number|boolean)[] = [1,true,2]; b) tuples let mytuple: [string,number,boolean] = ['Danny,1,true]; c) objects let person: { name: string; alive: boolean; }; person = { name:"Tom"; alive:true}; person.name = "Mike"; 3) interfaces interface Person { name: string; alive:true; sayHi(name:string):string; sayBye(name:string) => string; } let something:Person { sayHi: function (name:string) { return 'Hi ${name}'; } } usage: let person1:Person { name:"mike",alive:true}; d) functions function funcname(arg1:type,arg2?:type):return_type { } or with es6 const funcname = (arg1:type,arg2?:type):return_type => { } ? means optional argument. signature: let funcname: (arg1:type):null; e) types type PersonObject= { name:string; age: number; } f) classes class classname { private name: string; protected age: number; constructor(n:string,a:number) { this.name = n; this.age = a; } display() { return "Name: ${this.name} age:${this.age}"; } let people: Person[] = [person1,person2]; definition of scope of variables: readonly name: string; // This property is immutable - it can only be read private isCool: boolean; // Can only access or modify from methods within this class protected email: string; // Can access or modify from this class and subclasses public pets: number; // Can access or modify from anywhere - including outside the class g) generics const addID = let id = Math.floor(Math.random() * 1000); return { ...obj, id }; }; interface hasLength { length: number; } function logLength console.log(a.length); return a; } h) enums enum states { AL="AL",
Concise tutorial: https://www.freecodecamp.org/news/learn-typescript-beginners-guide/ |