Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Last active January 5, 2020 18:55
Show Gist options
  • Save rajaramtt/47aa259b511512d969e499c809c7e78e to your computer and use it in GitHub Desktop.
Save rajaramtt/47aa259b511512d969e499c809c7e78e to your computer and use it in GitHub Desktop.
Type Script

Annotations: TypeScript is statically typed and, therefore, all checks are performed at compile time. As mentioned before Types are annotated using :TypeAnnotation syntax.

Primitive Types

let isDone: boolean = false;

let decimal: number = 6;

let color: string = "blue";

Non Primitive Types

let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
  
JavaScript doesn't have first class tuple support.People generally just use an array as a tuple
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
  
//Enums 
  
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

//Number Enums
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;

//String Enums
enum Color {Red = 'red', Green='green', Blue='blue'}
let c: Color = Color.Green;
  
//Any  
we do not know when we are writing an application
These values may come from dynamic content, e.g. from the user or a 3rd party library
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

let list: any[] = [1, true, "free"];

//Void 

void is a little like the opposite of any 
You may commonly see this as the return type of functions that do not return a value:


function warnUser(): void {
    console.log("This is my warning message");
}


let unusable: void = undefined;
unusable = null; // OK if `--strictNullChecks` is not give

// Null and Undefined
In TypeScript, both undefined and null actually have their own types named undefined and null respectively. Much like void, they’re not extremely useful on their own:

As a note: we encourage the use of --strictNullChecks when possible, but for the purposes of this handbook, we will assume it is turned off.

However, when using the --strictNullChecks flag, null and undefined are only assignable to any and their respective types (the one exception being that undefined is also assignable to void). This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined, you can use the union type string | null | undefined.


//Never 
The never type represents the type of values that never occur
never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns

// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

// Function returning never must have unreachable end point
function infiniteLoop(): never {
    while (true) {
    }
}


//Object 

object is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined.

declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error


// Type assertions

/* Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.*/

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

Variable Declarations

let x = 10;
let x = 20; // error: can't re-declare 'x' in the same scope

function f(x) {
   let x = 100; // error: interferes with parameter declaration
}

function g() {
   let x = 100;
   var x = 100; // error: can't have both declarations of 'x'
}
 for (var i = 0; i < 10; i++) {
   // capture the current state of 'i'
   // by invoking a function with its current value
   (function(i) {
       setTimeout(function() { console.log(i); }, 100 * i);
   })(i);
}

for (let i = 0; i < 10 ; i++) {
   setTimeout(function() { console.log(i); }, 100 * i);
}

const declarations

same scoping rules as let, but you can’t re-assign to them.

const kitty = {
   name: "Aurora",
   numLives: numLivesForCat,
}

// Error
kitty = {
   name: "Danielle",
   numLives: numLivesForCat
};

// all "okay"
kitty.name = "Rory";
//the internal state of a const variable is still modifiable

Destructuring

Array destructuring
let input = [1, 2];
let [first, second] = input;
console.log(first); // outputs 1
console.log(second); // outputs 2

let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // outputs 1
console.log(rest); // outputs [ 2, 3, 4 ]

let [first] = [1, 2, 3, 4];
console.log(first); // outputs 1
Tuple destructuring
let tuple: [number, string, boolean] = [7, "hello", true];
let [a, b, c] = tuple; // a: number, b: string, c: boolean
Object destructuring
let o = {
   a: "foo",
   b: 12,
   c: "bar"
};
let { a, b } = o;

Default values

function keepWholeObject(wholeObject: { a: string, b?: number }) {
    let { a, b = 1001 } = wholeObject;
}

Function declarations

type C = { a: string, b?: number }
function f({ a, b }: C): void {
    // ...
}

Spread

// It allows you to spread an array into another array, or an object into another object.
let first = [1, 2];
let bothPlus = [0, ...first, 5];

let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };

Interface

function printLabel(labeledObj: { label: string }) {
    console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
// The printLabel function has a single parameter that requires that the object passed in has a property called label of type string. Notice that our object actually has more properties than this, but the compiler only checks that at least the ones required are present and match the types required. There are some cases where TypeScript isn’t as lenient, which we’ll cover in a bit.


interface LabeledValue {
    label: string;
}

function printLabel(labeledObj: LabeledValue) {
    console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

// Optional Properties

interface SquareConfig {
    color?: string;
    width?: number;
}

// Readonly properties
interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

let ro: ReadonlyArray<number> = a;//don’t change your arrays after creation
ro[0] = 12; // error!

//Excess Property Checks

interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any; 
}

let squareOptions = { colour: "red", width: 100 };
// any number of properties, colour the compiler won’t give you an error
let mySquare = createSquare(squareOptions); 
Readonly vs const

Variables use const whereas properties use readonly.

Function Types
interface SearchFunc {
   (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
   let result = source.search(subString);
   return result > -1;
}
//Indexable Types
interface NumberDictionary {
   [index: string]: number;
   length: number;    // ok, length is a number
   name: string;      // error, the type of 'name' is not a subtype of the indexer
}

//Class Types

interface ClockInterface {
   currentTime: Date;
}

class Clock implements ClockInterface {
   currentTime: Date = new Date();
   constructor(h: number, m: number) { }
}

//Extending Interfaces

interface Shape {
   color: string;
}

interface Square extends Shape {
   sideLength: number;
}

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
/****************not understanding********************/
//Hybrid Types
//Difference between the static and instance sides of classes
//Interfaces Extending Classes

Classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment