Mix and match types in a Typescript function

Typescript provides a convenient way to accept different types of arguments for a function, or to combine multiple types into one super type. Consider this example - function printThis(a: string) { return typeof a; } console.log(printThis("hello")); // string This function is fine if we want to return the input string for some strange reason. But, what if we want to generalise that function to - say, numbers? Union type In Typescript we can simply specify the argument as being string or a number using what is called “union type”. ...

Function overloading for optional arguments in Typescript

Overload functions to change signatures and provide optional arguments in Typescript. We have previously seen an option to provide optional arguments to a function in Typescript. But, there is more to that to function overloads. Building on our previous example - function getSum(i: number, j?: number, k?: number): number { j = j || 0; k = k || 0; return i + j + k; } console.log(getSum(1)); // 1 In the example, we have simply made j and k optional arguments and made their value 0 if they are not provided. Although this is evident for someone who looks at the function definition, it is not so for a person looking at the declaration or the auto-complete when initializing this function. ...

Duck typing in Typescript

Let us discuss everyone’s favourite topic since Typescript was invented - ‘duck typing’. Duck typing is type safety checks for complex types. It gets its name following the adage - If it walks like a duck and quacks like a duck, it must be a duck. Typescript modifies it slightly to - Don’t check whether it is a duck. If it quacks like a duck.. etc., it must be a duck Consider an example with a couple of variables of type objects and derived from a class. ...

Allow more or less no. of arguments in Typescript functions

Allow additional arguments or optional arguments for function calls in Typescript. Consider the below example of a function that adds two numbers. function getSum(i: number, j: number): number { return i + j; } console.log(getSum(1, 2)); // 3 This works fine and as expected, but what happens when there is a discrepancy in number of arguments. function getSum(i: number, j: number): number { return i + j; } console.log(getSum(1)); // error TS2554: Expected 2 arguments, but got 1. // An argument for 'j' was not provided. The above error is perfect. ...

Implicit return gotcha for arrow functions

Beware of using implicit returns in arrow functions. Consider the below example of a simple arrow function. It returns a simple variable. In the absence of any other statement in the function body, a simple mention of x will return the value of x. const getStuff = x => x; console.log(getStuff(1)); // 1 Let’s modify the block. We now want to return an object with the input value within it. const getMoreStuff = x => { x: x; }; console.log(getStuff(1)); // 1 Oops.. We expected {x: 1} but got 1 because the flower brackets were treated as enclosing a function body and not an object. ...

Public and Private Variables in Typescript

Are public and private variables really public or private? Consider the below example - class MathOp { public x: number; private y: number; } const op = new MathOp(); op.x; // no problem If you try to access the private variable.. op.y; // Error: Property 'y' is private and only accessible within class 'MathOp' What does private even mean? From our earlier definitions, the behaviour seems ok. Or, is it? Just compile the above code block to JS. tsc test1.ts And, the compiled Javascript file is - ...

The Different Types of Typescript

With ’type’ in its name, Typescript lives up to its reputation of being a typed language. But, what exactly are the supported types? At a high-level we can classify types as built-in (basic & special ) and additional types including user-defined types. Built-in Types (Basic) Similar to Javascript implicit types, we have number, string, boolean to form the three core built-in types. let num: number = 1; let planet: string = "earth"; let isHappy: boolean = true; We also have null, and undefined as additional basic built-in types. ...

Use onclick event instead of 'submit' in Javascript

Use onclick rather than submit in HTML forms. A typical HTML form has a few fields and a button to submit the data to some back-end server. And, the typical way to do the form submission is through the submit method. <form action="/helloMessage.php"> <input type="text" id="name" /> <button type="submit"></button> </form> On clicking the button, the page will submit data to helloMessage.php, receives any response from PHP page, and (can be configured to) displays the response. [Or, the page could redirect somewhere else based on the submission status, but we will not discuss that here] ...

Classes, Objects, Props and Interfaces in Typescript

Get started with object oriented programming in Typescript. Typescript behaves like a language with built-in support for OOP concepts, and does not carry the quirks of Javascript in that respect. Classes and Objects Define classes and objects like how you define in any of the popular OOP languages. class Fruit { public name: string; private grownIn: Array<string>; constructor(name: string, grownIn: Array<string>) { this.name = name; this.grownIn = grownIn; } getGrownIn(role: string): Array<string> { if (role == "admin") return this.grownIn; else return []; } private } let appleFruit = new Fruit("apple", ["India", "China"]); console.log(appleFruit.name); // apple We have defined a simple class ‘Fruit’ and provided it with - ...

What is Typescript and why should I care?

I had been fascinated by Typescript and have been going back and forth on making it my primary programming language. In a few posts and with as much less information as possible, let’s see why anyone should bother with Typescript. What is Typescript? Typescript is a typed Javascript. No, I am kidding - it is more than that. Typescript is not only strongly typed language that acts as a super-set of Javascript, but also is compiled and object oriented language. What distinguishes Typescript is not the language alone but the tooling that surrounds the language. ...