Few Tips to prevent runtime errors in Typescript

ยท

2 min read

Few Tips to prevent runtime errors in Typescript

#1 Prefer unknown over any

See this example on how any could go wrong.

const a: any = "dhslkd"

a.someMethod() // Runtime Error: a.someMethod is not a function

Oops! a does not have the someMethod but typescript doesn't care.

Let's try the same but with unknown.

const a: unknown = "dhslkd"

a.someMethod() // Compile Error: Object is of type 'unknown'.

Using unknown Typescript will throw an error during compilation! image.png

I would recommend using any type only when you really expect the value to be anything.

#2 Type Guards

In a typical web application, data is being transferred from one API endpoint to another, with no guarantee of the type of the received data.

Checking whether the fetched data from an API is of the expected type during runtime prevents a whole host of problems.

Typescript provides us a nice syntax for type checking.

interface SomeType {
   A: number;
   B: string;
}

// notice the return type annotation.
// Using this syntax makes typescript understand that the data is of type SomeType
function isSomeType(data: any): data is SomeType {
     return typeof data?.A === "number" && typeof data?.B === "string"
}

const data = fetch('/api/endpoint').then(res => res.json());

if (isSomeType(data)) {
     // data is of the expected form!
    console.log(data.A)
} else {
     // handle the error
    console.error("something went wrong")
}

#3 Testing, Testing, Testing

Testing is very important if you want to ship the code with more confidence and fewer bugs. Practicing TDD may increase your tech debt, but in the long run, it will pay you dividends!

If you have any tips to prevent runtime errors, do share them in the comment section.


Like this blog post if you found it helpful. It makes my day! ๐Ÿ˜ƒ