25 Tips and Tricks to Write Faster, Better-Optimized TypeScript Code
Tags: Typescript, React, Angular, Web Development, JavaScript

25 Tips and Tricks to Write Faster, Better-Optimized TypeScript Code

Optimize your TypeScript code using modern techniques, tips, and tricks

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. This can cover some frequently asked TypeScript interview topics in 2021. Moreover, these topics can help you to prepare yourself for JavaScript interviews in 2021.

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

1. How to convert an array of objects to object with key-value pairs?

We do have a lot of requirements for destructing array objects before using them in our application.

we can use Object.assign and a spread syntax ... for creating a single object with the given array of objects to achieve this function.

var data = [{ key1: "val1" }, { key2: "val2" }],

obj = Object.assign({}, ...data);



console.log(obj);

2. How to Exclude property from type interface?

We do typecast a lot in order to write cleaner code and we do use interface to achieve this, but sometimes we need to exclude some property of interface before using it.

We can use the omit property to exclude from the interface to achieve this function.

interface Interface {

val1: string

val2: number

} type InterfaceOmitVal1 = Omit<Interface, "val1">

3. How to import JSON file in TypeScript?

When we want to use any JSON file in our application we can use the following approaches.

declare module "*.json" {

const val: any;

export default val;

}

Then add this in your typescript(.ts) file:-

import * as val from './abc.json';

const test = (<any>val).val;

4. How to convert a string to a number in TypeScript?

There were a lot of times where backend services share us the string of numbers instead of a direct number. We do have the following ways to convert a string to a number.

There are a couple of ways we can do the same.

Number('123');

+'123';

parseInt('123');

parseFloat('123.45')

5. Is there a way to check for both `null` and `undefined` in TypeScript?

One of the best features I love to check multiple null, undefined, NaN,’’,0, and false in one shot using the below code.

if( value ) {

}

will evaluate to true if value is not:

null

undefined

NaN

empty string ''

0

false

typescript includes javascript rules.

To know about Angular Optimization Techniques Check out this series.

Understanding OnPush Strategy For Improving Angular Performance

We Should Not Call methods From Angular Templates

To know more about these techniques, Please check this article.

Understanding Memory Leaks in Angular

6. How to Enforce the type of the indexed members of a Typescript object?

We do use interface to enforce the type of the indexed members of Object.

interface dataMap {

[name: string]: number

} const data: dataMap = {

"abc": 34,

"cde": 28,

"efg": 30,

"hij": "test", // ERROR! Type 'string' is not assignable to type 'number'.

};

Here, the interface dataMap enforces keys as strings and values as numbers. The keyword name can be any identifier and should be used to suggest the syntax of your interface/type.

7. How can I create an object based on an interface file definition in TypeScript?

As we discussed a lot about typecasting, let’s see how we can create an object based on an interface file definition.

If you are creating the “modal” variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare const modal: IModal;

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

const modal: IModal = {

val1: '',

val2: '',

val3: '',

};

8. How to remove whitespace from a string in typescript?

we can use a Javascript replace method to remove white space like

"test test".replace(/\s/g, "");

9. How to ignore typescript errors with @ts-ignore?

We can change the ESlint rules to avoid the @ts-ignore issue.

We can disable the ESlint rule. Add that in your ESlint config ( .eslintrc or equivalent)

...

"rules": {

"@typescript-eslint/ban-ts-ignore": "off"

}

... OR "@typescript-eslint/ban-ts-comment": "off"

10. Is there a way to define a type for an array with unique items in typescript?

It can be achieved by creating a type function with extends InArray mentioned in the solution.

const data = ["11", "test", "tes", "1", "testing"] as const

const uniqueData: UniqueArray<typeof data> = data type UniqueArray<T> =

T extends readonly [infer X, ...infer Rest]

? InArray<Rest, X> extends true

? ['Encountered value with duplicates:', X]

: readonly [X, ...UniqueArray<Rest>]

: T type InArray<T, X> =

T extends readonly [X, ...infer _Rest]

? true

: T extends readonly [X]

? true

: T extends readonly [infer _, ...infer Rest]

? InArray<Rest, X>

: false

You’ll get a compiler error if the same value occurs more than once.

11. How to read response headers from API response in TypeScript?

Nowadays, we do have a lot of security on the frontend side, and one of the common methods we do use to implement security is the JWT token. We do get the token in the response header and when we want to decode it on the component side below is the most common method I found to this date.

In the Component.

this.authService.login(this.email, this.password)

.pipe(first())

.subscribe(

(data: HttpResponse<any>) => {

console.log(data.headers.get('authorization'));

},

error => {

this.isloading = false;

});

If you are looking for array and object-related tips please check out this article.

12. How can I check whether an optional parameter was provided?

As TypeScript provides the optional type in the function, a lot of time we need to check opposite conditions. When we want to check the optional parameter provided is null or not, we can use the below approach. It should work in cases where the value equals null or undefined :

function checkSomething(a, b?) {

if (b == null) callMethod();

}

13. How to restrict type with no properties from accepting strings or arrays?

When we do have an interface but we want to restrict the strings or arrays or any specific types, How we can extend our interface?

Let’s consider the following example where to want to restrict object or array.

interface Interface {

val1?: number;

val2?: string;

} function Change(arg: data) {

} Change("test");

We can do something like this to make Change accept at least an object:

interface data {

val1?: number;

val2?: string;

} interface notArray {

forEach?: void

} type type = data & object & notArray; function test(arg: type) {

} test("test"); // Throws error

test([]); // Throws error

14. How to use Map in TypeScript?

TypeScript supports something called Record . It natively works as Map and supports our function. Below is the example for Map in TypeScript.

type dataType = Record<string, IData>;

const data: dataType = {

"val1": { name: "test1" },

"val2": { name: "test2" },

};

15. How to initialize Map from an array of key-value pairs?

As typecasting is a hot topic to maintain clean code if we want to typecast array key-value we can follow the below approach.

const data = [['key1', 'value1'], ['key2', 'value2']] as const;

Or, we can create like this.

const data: Array<[string, string]> = [['key1', 'value1'], ['key2', 'value2']];

Or, if you need to preserve the keys/values exactly:

const data = [['key1', 'value1'] as ['key1', 'value1'], ['key2', 'value2'] as ['key2', 'value2']];

Recently, I was trying to prepare myself for the upcoming interviews and it was a bit tough to search in google and open link and see same questions each and every time so I thought of sharing what I have found and what is most common questions someone should know if they are preparing for an interview.

Below are the most common interview questions asked in Latest Angular Developer Interviews. These Angular Interview questions and answers help to prepare for Angular developer interviews from junior to senior levels. Moreover, this article covers the basics to advance angular interview questions which you must prepare in 2021.

16. How to create an instance from the interface?

If we want to create an instance from the Object we can use the following two approaches.

interface IData{

val1: number;

val2: string;

}

then

var obj = {} as IData

var obj2 = [] as Array<IData>

17. How can I cast custom type to primitive type?

We can create a type of specific numbers and pass that type to the creation of a variable like this.

type Data = 0 | 1 | 2 | 3 | 4 | 5;

let myData:Data = 4

let data:number = myData;

18. How to add if else condition in the Observable?

we can add a switch map to check where the observable got value or not. Let’s check the below example.

this.data$

.pipe(

switchMap(() => {

if (canDeactivate) {

return Observable.of(canDeactivate);

}

else {

return Observable.of(window.confirm("test"));

}

})

);

Or we can write like this.

this.data$.pipe(

switchMap((canDeactivate) => Observable.of(canDeactivate || window.confirm("test"))

);

19. How to use a generic parameter as an object key?

As we are concentrating more on typecasting let’s see if we want to typecast the object key.

Let’s see an example where we have the response coming from the GraphQL and we want to create a type for the response coming dataId This can be achieved using the following ways.

QueryKey extends string key in QueryKey

interface GraphQLResponse<QueryKey extends string, ResponseType> {

data: {

[key in QueryKey]: ResponseType;

}

} interface User {

username: string;

id: number;

} type dataIdResponse = GraphQLResponse<'dataId', User>;

Example:

const dataIdResponseResult: dataIdResponse = {

data: {

dataId: {

id: 123,

username: 'test'

}

}

}

20. 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 objects to the 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}'.`);

}

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

});

}

}

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

23. 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`;

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

}

25. How to get the names of enum entries in TypeScript?

Yes, when we have used enum most of the 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];

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