Skip to main content

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

Popular posts from this blog

Powerapps overcome 2000 item limit from any datasource

First go through delegation concept https://tejasadventure.blogspot.com/2020/05/power-apps-understanding.html In powerapps, we observe by default 500 item limit has set with in the app level for any data source. In order to overcome, we have option to set the limit of 2000 item limit maximum in the app. Now using code, MaximoFacility is my data source name contains 3000 items. ColFacilityDropdown is the collection storing the count of items from data source. We expect to see more than 2000 items. Based on StartWith function filtering the data with respective to the charectors and numbers as mentioned below. Code: Place the below code in a button on select property. Add label with code CountRows(ColFacilityDropdown) ClearCollect(ColFacilityDropdown,Filter(Filter(MaximoFacility, Status = "ACTIVE"), StartsWith( Title, "A" ))); Collect(ColFacilityDropdown,Filter(Filter(MaximoFacility, Status = "ACTIVE"), StartsWith( Title, "B" ))); Collect(ColFacilit...

Power Apps Understanding

https://tejasadventure.blogspot.com/2019/10/power-apps-we-have-1.html https://tejasadventure.blogspot.com/2019/11/power-apps-how-to-configure-using-blank.html   https://tejasadventure.blogspot.com/2019/11/power-apps-field-controls.html Report We can use people picker fields, look up fields  file attachment back next save cancel download the report and this report can be used in other system of powerapp. Add new report button - asks add from existing report Report all item view can design in the way like sharepoint list views for example. we can group it Group AND or Group OR by apply filters Canvas apps: Arrange user experience and interface design allow creativity and business use case guide how the way app wants to look like. Sources can be around 200+ ways. Majorly SharePOint, Power BI From data, From Sample From CDS From blank canvas via appSource Model driven apps: Model driven apps uses power of CDS rapidly to configure your for...

PowerApps multiselect cascading dropdown and save an item to SharePoint List

 I have one scenario as below List 1: Division List has title field List 2: District List has Title and Division Field(LookUp from Division List) List 3: Facility List has Title, District Field(LookUp field from District List) List 4: County List has Title, Facility Field(LookUp field from Facility List) Main List: Spill Report is the main list  Division Field( Look up from Division List) District Field(Look up field from District List) Facility Field(Look up field from Facility List) County Field(Look up field from County List) List Screenshots provided below can be refered for clarification. ----------------------------------------------------------------------------------------------------- PowerApps Canvas Apps In Power Apps Canvas App, We need to first design the app with the 4 respective fields Since those fields are multiselect, then it is to combo box. Generally power apps are not supported for multiselect cascasding dropdown. Refere microsoft documentation, Know Limit...