TypeScript

TypeScript

An introduction to the world of type safe JavaScript.

You might have heard of TypeScript, even tried your hands at it, and not understand it. Well, it happened to me too. The thing is you have to know what something is before understanding what it can do. Note that this is an introduction and does not include how to set up Typescript in a project.

What is TypeScript?

TypeScript is simply Javascript with "optional" static typing. The word optional is in quotes because it is not always optional to add type to variables. TypeScript adds an explicit type system to JavaScript, allowing for the strict enforcement of variable types. TypeScript itself is useless to the browser or Node.js, it compiles to Javascript to be useful. TypeScript runs its type checks while transpiling —a form of compiling that converts TypeScript code to the JavaScript code web browsers and Node.js understand. The main benefit of Typescript is that it can highlight unexpected behaviour in your code and reduce the chances of having bugs.

TypeScript vs Javascript

Advantages of TypeScript

  • Easy debugging: This tops the list for me. TypeScript catches errors in development meaning you don't have to push bad code to your repo. And if you are that developer who runs builds locally before pushing, you're less likely to have errors.

  • Extended language features: TypeScript provides some features unavailable in Javascript. Abstract classes, type, and interface are a few of the TypeScript language features that make development easier.

  • Scalability: TypeScript makes it easier to scale than Javascript in refactoring, reference validation and documentation.

  • ES6 Modules: Whether front- or back-end, you can use ES6 modules anywhere. The transpiled output will be compatible with the selected environment, e.g., module, CommonJS.

  • Class-Based Objects – Another significant benefit is the utilization of Classes, which enables us to implement genuine object-oriented programming within our applications and discourages the use of prototype-based objects. This approach also offers features like encapsulation, inheritance, and modifiers.

Disadvantages of TypeScript

  • Potential workflow incompatibility: This is pretty common with third-party libraries.

  • Runtime errors may still occur: you may experience peculiar runtime errors that you may face in Javascript here too as all type of checks are scrapped off after transpiling.

  • Combining JS and TS: In a case where converting a .js file .ts may not be the best thing maybe because the file would require significant reverse-engineering to convert or something similar, a type declaration file d.ts would need to be provided as in the case of React and Lodash.

TypeScript Syntax

In Javascript, variable declaration and initialization are very flexible.

let var1 = "Hello"
var1 = 10
console.log(var1)

Here, var1 starts as a string and then becomes a number. Since JavaScript is only loosely typed, we can redefine var1 it as a variable of any type — from a string to a function — at any time. This is perfectly okay in Javascript because all values are compiled at runtime, and the code above will log 10 in the console. But with TypeScript, you have this:

let var1:string = "Hello"
var1 = 10
console.log(var1)

In this case, we declare var1 to be a string. We then try to assign a number to it, which isn’t allowed by TypeScript’s strict type system. This is a very feature because it will help you assert types and keep errors to the barest minimum. Transpiling results in an error:

TSError: ⨯ Unable to compile TypeScript:
src/snippet.ts:2:1 - error TS2322: Type 'number' is not assignable to type 'string'.

2 var1 = 10;

If we wanted the Typescript transpiler to treat the code like the Javascript snippet, we would use a union type, allowing us to assign more than one type to a variable.

let var1: string | number = "Hello"
var1 = 10

We can also add types to objects to get auto-complete and avoid typos. We can declare a type by using the type keyword.

type User = {
    id: string
    name: string
    role: "user" | "admin"
}

const user: User = { id: "1", name: "Bob", role: "admin" }

Typescript has some advance variable types, including Tuples, Enums, Unions, Intersection, Type Aliases, Generics, Mapped Types, and Discriminated Unions.

Tuples

A tuple is an ordered list of elements, where each element can have different data type. It is similar syntax to Array, except an array is homogenous, i.e., its elements must be of the same data types. If you're a React person, you would have come accross tuples. The return value of the useState hook is a tuple; it looks like an array but the first element is the getter or the current value, while the second element is the setter or function to update the state.

const person: [string, number] = ["John", 30]

Enums

Enumerators or enums for short allows the definition of a set of named constants. They are useful for representing a fixed set of values.

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

const direction: Direction = Direction.Up

Conclusion

Typescript can seem quite overwhelming at first, but trust me, it isn't as hard as you think. And it is very useful tool to have in your toolbox as a JavaScript developer. Take your time, learn it and make it work for you.

If you have any suggestions or feedback, please feel free to drop a comment or reach out to me on Twitter, @pablo_clueless.