How to convert your JavaScript object literals to Typescript

Converting your object literals to the typescript side

RamaDevsign (Rama Ochieng)
3 min readApr 14, 2022

What is an object literal?

A JavaScript object literal is a comma-separated list of name-value pairs encapsulated inside curly braces, kind of like a JSON structure.

object literal in JavaScript

The above snippet demonstrates how you can declare an object literal and access its contents. The above only applies in a JavaScript environment so if we want to convert it to typescript we will have to first change the file extension from .js to .ts

object literal in typescript(with errors)

On trying to access the object member “phone” after the conversion, typescript threw an error. I wasn’t also able to add a new object member “city” either.

Strategies for converting to typescript.

We can make use of two strategies when converting our object literals to typescript. The first strategy will be the any type and the second strategy will be by using an interface.

Strategy 1: using type any

object literal in typescript with type any

When you use type any, all errors which were thrown earlier will disappear, meaning that you can access the non-existing member and you can also add new members to your object literal.

Using type any will temporarily “fix” the errors thrown but is an anti-pattern because is removes all the type checking which is provided by Typescript.

Strategy 2: Using an interface

object literal in typescript with interface

A good way to declare the member objects inside your object literals is through an interface. It makes your code look clean and you also get type safety and code documentation which improves the overall developer experience as the project grows with time.

You can also include an optional object member inside the interface so that typescript doesn’t throw an error incase it doesn’t get the specified object member.

You can also opt to declare your interfaces in a different file then import them in order to separate the interfaces and code logic.

I hope this short write up was helpful to you and happy coding!!

--

--

RamaDevsign (Rama Ochieng)

I am a software developer creating beautiful experiences on the web. Co-organizer: Reactjs Developer Community Kenya ||