TypeScript


Visual studio code extensions useful for typescript coding.

Path intellisense
ESlint
Material theme icon
Prettier-code form

How to run typescript application in local server?


What ever the changes we made in our code will automatically reflect in the browser, For this setup, we need a local server make it ready in our local machine that can run on local browser. We have to install lite-server in machine from NPM and servers us dynamic changes in code reflect in the browser of local machine.
Use the below commands for the setup.
node -v
npm -v
npm install npm@latest -g
npm init --yes
npm install lite-server --save-dev

install tsconfig.json tsc --init.


NOTE:

const variable values cannot be changed.
let is the key word where the variable will be available in that block.
But let support for all the types
String[] // means array of strings are storing in a variable
Any[] //means flexible for any types of array


public is the keyword, it will automatically make the public variable available if we use it in any return statement.

class Students {
    fullName: string;
    constructor(public firstName: string, lastName: string){
        this.fullName = firstName +" "+lastName;
    }
}

let user_for_class = new Students("Koti","Saga");
console.log(user_for_class);

Here result is 

Students {firstName: "Koti", fullName: "Koti Saga"}


here firstName is kept public

NumberStringBoolean

Object {'aga':30}

example:
const personIs:{
    "Name":string,
    "Age":number
} = {
    "Name":"Saga",
    "Age":29
}
console.log(personIs.Name);
//nested object
const product = {
    id: 'abc1',
    price: 12.99,
    tags: ['great-offer''hot-and-new'],
    details: {
      title: 'Red Carpet',
      description: 'A great carpet - almost brand-new!'
    }
  }
document.getElementById("mycontent").append(personIs.Name);


Array
example:
//Arrays
const person = {
    "name":"Saga",
    "age":29,
    "hobbies":["cooking","eating"]
};
let favourateActivities :string[];
favourateActivities = ["Watching TV","Reading News"];
for(const hobby of person.hobbies){
    console.log(hobby.toUpperCase());
}

Tuples //Tuples are fixed length arrays. It can first type number and second type can be string and always 2 
values in an array as we declared two types.

enum // enum always accept capital for first variable

example:
//Arrays
enum Myrole { ADMINREAD_ONLYAUTHOR
const person1 :{
    "name":string,
    "age":number,
    "hobbies"string[],
    "role": [numberstring]
    "personrole":any
} = {
    "name":"Saga",
    "age":29,
    "hobbies":["cooking","eating"],
    "role":[2,"admin"],
    "personrole": Myrole.ADMIN
};
person1.role = [3,"developer"];

let favourateActivities1 :string[];
favourateActivities1 = ["Watching TV","Reading News"];

let myvariable : any[]
for(const hobby of person1.hobbies){
    console.log(hobby.toUpperCase());
}
if(person1.personrole === Myrole.ADMIN){
    console.log("is author");
}

Any // any can store any of type but the main typescipt other properties we can't experience if we use type any frequently in our code.
Union type //

Union types with Literals

example:


//Literal types with respective to UNION types
function combine(
    n1 :number | string
    n2:number | string,
    resultConversion'as-number' | 'as-text'//these are union type with 2 literals
)
{
    let result;
    // basic type check. Now we can use UNIONS.
    console.log(typeof n1 +", "typeof n2 +" ,"typeof resultConversion);
    if(typeof n1 === "number" && typeof n2 === "number" || resultConversion === "as-number"){
        result = +n1 + +n2;// adding + infornt of n1,n2 is because to enforce to consider as number
    }
    else{
        result = n1.toString() + n2.toString();
    }
    return result;
}


const combineAge = combine(30,26,'as-number');
console.log(combineAge);
const combineAge1 = combine("30","26",'as-number');
console.log(combineAge);


const combineAgewithString = combine("Saga ","Teja",'as-text');
console.log(combineAgewithString);

Custom TYPES and Literal types defined as custom type

    
//Custom Types and Literal types defined as custom type
type comibinable = number|string;
type conversionDescriptor = 'as-number' | 'as-text';


function combine(
    n1 :comibinable
    n2:comibinable,
    resultConversionconversionDescriptor//these are union type with 2 literals
)
{
    let result;
    // basic type check. Now we can use UNIONS.
    console.log(typeof n1 +", "typeof n2 +" ,"typeof resultConversion);
    if(typeof n1 === "number" && typeof n2 === "number" || resultConversion === "as-number"){
        result = +n1 + +n2;// adding + infornt of n1,n2 is because to enforce to consider as number
    }
    else{
        result = n1.toString() + n2.toString();
    }
    return result;
}


const combineAge = combine(30,26,'as-number');
console.log(combineAge);
const combineAge1 = combine("30","26",'as-number');
console.log(combineAge);


const combineAgewithString = combine("Saga ","Teja",'as-text');
console.log(combineAgewithString);


Example 2:
//Example 2


type currentUser = {
    namestring,
    agenumber
}
const currentUserVar:currentUser = {
    name:"Saga",
    age:28
}
currentUserFunc(currentUserVar);
function currentUserFunc(usercurrentUser){
    console.log("Hi, the user name is "+user.name);
}

Function return types & Void & Call back function

If void is there then it does not need to return any thing.

example
function add(n1number,n2:number){
    return n1 + n2;
}
function printResult(resnumber):void{
    console.log("Result is "+res);
}
printResult(add(3,5));



call back function

Function types define the parameters and return type of a function.
example

//Call back function
//void represents it doesn't need to return any thing
function handleCaliculation(n1numbern2numbercb:(numnumber)=> void){
    const resultI = n1 + n2;
    cb(resultI);
}


handleCaliculation(10,20, (result=>{
    result  = result + 100;
    console.log(result);
});

Unknown type

//Unknown type is one of the type in typescript

let userInputunknown;
let userNamestring;

userInput = "Saga";
userInput = 28;
if(typeof userInput === "string"){
    userName = userInput
}
console.log(userName);

NEVER type

//Never type
//function which doesn't need to return any thing
function generateError(messagestringcodenumber): never {
    throw { message:messageerrorCode:code }
}


generateError("An error occured",500);

Further Type references:






Comments