5 mistakes you shouldn't do in TypeScript
If you are a frontend developer and not living under a rock since last couple of years, you know that TypeScript has emerged as a de-facto standard when it comes to writing type safe Javascript code.
While most folks put deliberate efforts to learn Javascript, same isn't true for TypeScript. It is generally an after-thought. Oh, I am getting this TypeScript error, let's see what I can do to fix it. Ironically, that's a wrong way to code. TypeScript gives you a powerful way to talk to yourself (or someone else) in future and warn about mistakes as and when you commit them. However, in order to get this benefit, you need to be intentional about putting the right checks in place using TypeScript.
Here are some of the most common mistakes even experienced TypeScript developers make that you shouldn't.
1. Using type assertions instead of type declarations
Let's quickly go over what is type declaration
and type assertion
.
Type Declaration
is when you simply define a type for a variable using the :
operator. For example, const user: IUser = {id: "123", name:"Harshit Jain"}
. Here the interface IUser
is used as a type for variable user
.
Type Assertion
is when you use the as
keyword. For example, const user = {id: "123"} as IUser
. Here you are telling Typescript that you know better than the typescript compiler and that it should assume the value matches the type.
Type assertions are useful when you really know better than the typescript compiler, for example when you are using some 3rd party library that doesn't have types or let's say you get some data from an API endpoint. Other than that, you should always prefer using type declaration so that Typescript can do it's job i.e. match the value with the provided type and flag any errors.
2. Using the Function type TBA 3. Using wrapper objects instead of primitives TBA 4. Repeating interfaces TBA 5. Repeating properties or value types TBA