typescript course for beginners 2021

    By: Manu
    2 years ago

    TypeScript helps us to check our code for data types. hmm what it means. Nothing can explain better than a code example so here it is

    // Have a look
    
    // Code in javascript
    
    let userName = 54;
    

    Something not right, UserName should be a string and it suppose to be a name such as "Manu" or "Roger" or any other human name but should not be a number. But javascript will give green light to above code. Hmmm

    TypeScript Benefit

    Now see what if user tries to do same thing in typescript.

    // Code in TypeScript
    
    let userName:string = 54;  // Cannot assign number to userName.
    

    TypeScript tells us that we are not allowed to use number where string is expected. and that is what TypeScript id designed for.

    Data validation in typescript

    We can check for different data types in typescript such as

    // boolean                // true or false
    // number or number[]     // Here number or array of number
    // string or string []    // String or array of string   
    

    Let's see how we can use typescript in functions for checking if right data type is provided.

    // First create an interface.
    
     interface UserData 
     {
          accountNumber: number,
          name: string
     }
    

    Here we created an interface "UserData". Now we expect data to be "accountNumber" and "name" and data types should be number and string. So to now we can use this interface in our code to check if we get data in same format or not.

    let accountNumber = 4524234424;
    let name = 'some text';
    
    // here we called "UserData" interface and now data should have like UserData interface.
    
    let data:UserData = { 
          accountNumber, 
          name
        };
    

    So if "accountNumber" is not number we will see error and if "name" provided is not type string again we will get error.

    Hope this explains the typescript concept for more understanding check out our video Guide.