Improve Your TypeScript: Part One

JavaScript vs TypeScript

Let’s start by tackling the differences between JavaScript and TypeScript. Wikipedia: “It is a strict syntactical superset of JavaScript…”. To keep it short 😉, all JavaScript is valid TypeScript. You can say TypeScript is a layer on top of JavaScript.

TypeScript Options

If you have been working with TypeScript, you have probably come across this:

TypeScript implicit Any Type Error.
TypeScript Implicit Any Type Warning
Enable strict option typescript
Typescript throwing warning as errors

Code generation is Independent of Types

tsc, the TypeScript compiler converts your TypeScript/JavaScript into JavaScript that is understandable to the browser. It is that code that the browser will get and execute, to clarify, the code TypeScript will emit.
Because it is JavaScript that gets executed, the types TypeScript gives you can not affect the way your code runs, i.e. do not prevent your code from not getting executed.
TypeScript errors are similar to warnings in other languages like C or Java, just because it is spitting an “error”, does not stop the build when the code gets executed.
As long as your TypeScript is valid JavaScript, the TypeScript compiler will produce output, even if TypeScript is spitting errors at you.
TypeScript types and type operations are removed when TypeScript compiles into JavaScript during runtime, therefore they have no effect on runtime performance.

Checking for types during runtime

If you really wanna check for types during runtime, you can include a “tag” in the interfaces:

Tag on Interface TypeScript
Using Tag on Interfaces

Declaring typed functions

You can create multiple declarations for a function but only a single implementation. Declarations describe the functions inputs and the value they return.

function declarations typescript
Function declarations TypeScript

Avoid any type

Japp 😝! Avoid the “any” type as much as possible. It might seem like it is easier to work with typescript because you get to avoid many silly errors it will spit at you 😕, but it will actually take away the comfort and safety TypeScript offers.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store