What is Static Typing in TypeScript


What is TypeScript?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. TypeScript is pure object oriented with classes, interfaces and statically typed like C# or Java.

Static typing in Typescript

Code written in Typescript  is Static typing means you can declare the variable & compiler will take care of assigning the type of values.

Create any empty project using Visual studio 2015 / 2017
Step 1: Now add one typescript file into it & write code as below.

I am giving the name to above file Static_Typing.ts

class Person {
    getDetails(id: number, name: string): void{
        alert("Your Id is: " + id + " & Name is: " + name);
var objPerson = new Person();
objPerson.getDetails(1000, 'Rupesh Kahane');

Note: In above typescript file, I have written one function i.e. getDetails() which has two parameters Id as number & Name as string.  This function is in class Person & outside the class, I have just created object of that class & passed the parameters.

Typescript can help to write programs using Object Oriented Programming & compiled it to Javascript, which is very to use who knows the OOPS concept.

Step 2:  Now add an HTML page to your solution. In that just drag & drop the above typescript file.

<!DOCTYPE html>
  <meta charset="utf-8" />
    <script src="Static_Typing.js"></script>
    <h2> Demo of Static Typing in Typescript</h2>


Step 3: After compilation of above typescript code is converted into a javascript file as bellow

var Person = (function () {
    function Person() {
    Person.prototype.getDetails = function (id, name) {
        alert("Your Id is: " + id + " & Name is: " + name);
    return Person;
var objPerson = new Person();
objPerson.getDetails(1000, 'Rupesh Kahane');

Very Imp:  

  • Here you can see in javascript function the types are completely removed from the function.
  •  If user omitted the type of declaration then compiler will inferred automatically from your code as like
var name = ‘rupesh’;
  • If you trying to assign some illegal values then at the time of compilation tsc will gives you warning as
var IsActive: boolean = 'Rupesh';
  • If you pass a different parameter to function then it will give also warning. For example consider above function & if you try to pass both parameters as string like
objPerson.getDetails('1000', 'Rupesh Kahane');

See your function has a parameter getDetails(number, string) so that’s why at the time of compilation it shows warning.

Step 4:  Run your application You will get result as .

Conclusion: In this article you learn what is Static Typing in TypeScript.


Please enter your comment!
Please enter your name here