TypeScript Tips, Tricks, and Best Practices
Tags: Front End Development, Angular, Typescript, JavaScript, Interview

TypeScript Tips, Tricks, and Best Practices

Part 1

I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I create tips for day to day Frontend development.

You might be doing angular development for a long time but sometimes you might be not updated with the newest features which can solve your issues without doing or writing some extra codes. This can cover some frequently asked Angular topics in interviews.

Here I am coming with a new series to cover some tips which helped me in my day-to-day coding.

How to cast a JSON object to a TypeScript class?

To write a clean code we need to typecast properly. Here are different methods to cast JSON object to TypeScript class.

Considering the following interface and a silly JSON object (it could have been any type):

interface Interface {

val: string;

} const json: object = { "val": "value" }

A. Type Assertion or simple static cast placed after the variable

const obj: Interface = json as Interface;

B. Simple static cast, before the variable and between diamonds

const obj: Interface = <Interface>json;

C. Advanced dynamic cast, you check yourself the structure of the object

function isInterface(json: any): json is Interface {



return typeof json.key === "string";

} if (isInterface(json)) {

console.log(json.key)

}

else {

throw new Error(`Expected MyInterface, got '${json}'.`);

}

How to load external scripts dynamically in TypeScript?

The most elegant solution to load the external scripts is to use a third-party library named script.js.

It can be done by following simple steps to install the script.js library.

Step 1:

npm i scriptjs npm install --save @types/scriptjs

Step 2:

Then import $script.get() method:

import { get } from 'scriptjs';

Step 3:

export class TestComponent implements OnInit {

ngOnInit() {

get("https://maps.googleapis.com/maps/api/js?key=", () => {

//Google Maps library has been loaded...

});

}

}

How to concatenate two or more string literal types to a single string literal type in TypeScript?

You can now use template string types to do this:

function createString<val extends string, val2 extends string>(data: val, name: val2) {

return data + '/' + name as `${val}/${val2}`

} const newVal = createString('abc', 'cde');

// const newVal: "abc/cde"

How to make one string by combining string and number in Typescript?

As ES6 introduced the String literals we can use that to combine any number and string to make one string.

Your string concatenation then turns into this for example:

str = `${number}-${number}-${number} string string string`;

How to dynamically assign properties to an object in TypeScript?

Playing with Object is one of the common tasks every Frontend developers do in their daily routine.

Below are different ways we can dynamically add a property to an array of objects.

1. Index types

interface MyType {

typesafeProp1?: number,

requiredProp1: string,

[key: string]: any

} var obj: MyType ;

obj = { requiredProp1: "foo"}; // valid

obj = {} // error. 'requiredProp1' is missing

obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number obj.prop = "value";

obj.prop2 = 88;

2. Record<Keys,Type> utility type

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {

typesafeProp1?: number,

requiredProp1: string,

}

How to get the names of enum entries in TypeScript?

Yes, when we have used enum most of time we don’t care about the key but sometimes we need to get values dynamically from the key to fetch the values.

For me, an easier, practical, and direct way to understand what is going on, is that the following enumeration:

enum colors { red, green, blue };

Will be converted essentially to this:

var colors = { red: 0, green: 1, blue: 2,

[0]: "red", [1]: "green", [2]: "blue" }

Because of this, the following will be true:

colors.red === 0

colors[colors.red] === "red"

colors["red"] === 0

This creates an easy way to get the name of an enumerated as follows:

var color: colors = colors.red;

console.log("The color selected is " + colors[color]);

It also creates a nice way to convert a string to an enumerated value.

var colorName: string = "green";

var color: colors = colors.red;

if (colorName in colors) color = colors[colorName];

How to write get and set in TypeScript?

TypeScript uses getter/setter syntax that is like ActionScript3.Most of the time getter and setter used to make private variables inaccessible or modified by the outer world. Below is an example of common getter and setter syntax in TypeScript.

class foo {

private _bar: boolean = false;

get bar(): boolean {

return this._bar;

}

set bar(value: boolean) {

this._bar = value;

}

}

References:

Are you preparing for interviews? Here are frequently asked interview questions in Angular. It covers the Latest interview questions for Angular and Frontend development. Let’s check how many of these questions you can answer?