Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

let in TypeScript

TypeScript (and ES6) introduces the let keyword to allow you to define variables with true block scope. That is if you use let instead of var you get a true unique element disconnected from what you might have defined outside the scope.

Following example code example demonstrates use of “let” which is truly block scoped.

Function getUserNameWithLet() returns username "nmk" which is block scoped.

Typescript Code:

function getUserNameWithVar()
{
    var userName = "ken";
    if (true) {
       var userName = "kendre";
    }
    return userName;
}
 
function getUserNameWithLet() {
    let userName = "nmk";
    if (true) {
        let userName = "kendre";
    }
    return userName;
}
 
window.onload = () => {
    var elNameWithVar = document.getElementById('lblFirstNameWithVar');
    var elNameWithLet = document.getElementById('lblFirstNameWithVar');
    elNameWithVar.innerHTML =getUserNameWithVar();
     elNameWithLet.innerHTML =getUserNameWithLet();
};

HTML code:

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="LetExample.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>
 
<label id="lblFirstNameWithVar"></label>
<label id="lblFirstNameWithLet"></label>
</body>

Interfaces in TypeScript

Interfaces provide the ability to name and parameterize object types and to compose existing named object types into new ones.

Interfaces have no run-time representation—they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.

Here we use an interface that describes objects that have a firstName and lastName field. In TypeScript, two types are compatible if their internal structure is compatible. This allows us to implement an interface just by having the shape the interface requires, without an explicit implements clause.

Typescript interface code example:

interface IEmployee {
    firstName: string;
    lastName: string;
}
 
function getFullName(person: IEmployee) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
 
var user = { firstName: "Shourya", lastName: "Kendre" };
 
window.onload = () => {
    var elFullNameName = document.getElementById('lblFullNameName');
    elFullNameName.innerHTML = getFullName(user); 
};


HTML code:

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="InterfaceExample.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>
<label id="lblFullNameName"></label>
</body>
</html>


Result Page:


धन्यवाद मित्रानो !!!