Typing collections in Typescript

How are collections typed in Typescript? Primitives are fairly easy to type - we have seen this while discussing Typescript and its types. const num: number = 0; const msg: string = "hello"; We have seen examples of typed arrays in the same post, but how about all the other collections? How far down the typed rabbit hole are you willing to go? Arrays There are two useful notations - pick one, or both. let num: number[] = [1, 2, 3]; const numToo: Array<number> = [1, 2, 3]; Tuples Tuples, unlike arrays, have fixed number of elements. In Typescript, we just go about typing all of them. ...

Access modifiers in Typescript

Typescript supports public, private and protected modifiers that affect the accessibility of class in different ways. Access modifiers further a core concept of object oriented programming - ’encapsulation’. The accessibility of variables and members of a class are driven by modifiers and therefore controlled in the programming flow. Let’s start with a simple class example. class MathOp { public x:number; private y: number; protected z: number; } Public modifier All variables and members are public by default in Typescript. ...

Static variables and methods in Typescript

Typescript allows use of static variables and methods just like modern Javascript. Static variables and methods are declared with a keyword static. Static variables Static variables exist within the class context, and are not carried forward to the object of the class. Define a static variable like so - class Human { static chaos: boolean = true; } The variable value is accessible using the class. console.log(Human.chaos); // true .. but not against the object. const joe = new Human(); console.log(joe.chaos); // error TS2576: Property 'chaos' is a static member of type 'Human' If you need a value in the object no matter the costs, you can always have the two variables with same names. ...

Type Assertion in Typescript

Typescript’s type assertion features help us to override type inference and indicate a specific type to a variable. Type assertion may not be the most common of the features you employ, but it is invaluable when you are migrating from Javascript. Or, when you have to interact with Javascript libraries or data from external systems in your Typescript code. Take note of one important thing though - since all Typescript code is compiled to Javascript, any and all assertion is applied at compile time. There is no runtime type assertion. ...

Initialize empty object and add props

There are situations when you need to initialize object without props. How do you manage that it Typescript? Let’s consider the example below. First, we declare the object and initialize it to an empty object. const planet = {}; Then, we add the props - planet.name = "earth"; The above initialization + assignment combination is perfectly valid in Javascript. But Typescript does not agree with planet.name since the object was declared as type {} (an empty object). ...

Readonly Properties in Typescript

Typescript provides a way to indicate props in an object / type, or an entire type, as read only. Props in an object Consider this example - class Fruit { readonly name = "apple"; color = "red"; } In the code block we have specified the prop name as read-only. We can very much change the color of an object derived from Fruit. const apple = new Fruit(); console.log(apple); // Fruit { name: 'apple', color: 'red' } apple.color = "blue"; console.log(apple); // Fruit { name: 'apple', color: 'blue' } But, we cannot change the name - ...

Typeguards in Typescript

Typeguards enable us to process function arguments based on their types. Consider this example - function join(a: string): string { return a; } console.log(join("hello")); // hello What if we want to use join for strings or numbers? We can do a union type like so - function join(a: string | number): string | number { return a; } console.log(join("hello")); // hello console.log(join(1)); // 1 But, a real world problem would lie in processing the input arguments - not just returning them. Also, the methods and properties of the argument will change within a function based on their types. Typescript solves this problem using Typeguard. ...

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. ...