Typescript first impressions

31 Dec,2019 | 6 min read

I appreciate JavaScript's versatility and the speed it offers when developing software. However, this speed comes with tradeoffs, and one of the core tradeoffs, similar to that of any dynamic language, is the absence of a type system. I often find myself jumping between files to ensure I'm adhering to the correct function signatures, which increases cognitive load. Additionally, I've felt a sense of uncertainty about how well my software is functioning due to the frequent TypeErrors I encounter.

To address this issue, I had two solutions to choose from: Flow by Facebook and TypeScript from Microsoft. I opted for TypeScript due to its large community and rich ecosystem.

What is Typescript

Typescript is a superset of Javascript, adding a bunch of features on top of the core JavaScript functionality. Among my favorites, of course, is the type system and all the benefits we derive from it. By the way IntelliSense with Typescript is 👌.

Now let's take a quick look at some of the basic but cool features of Typescript's type system

Type Queries

The typeof operator is used in javascript to return the type of its operand, in Typescript the keyword typeof is very different. Copy and paste this code in .ts file, you will see that typescript inferred { number, string, number } as the type of the house, and that’s what I want, we can easily get that type with the typeof keyword.

const house = { id: 34345, address: " 3B Col, 90000 ", members: 4 };
type House = typeof house;

Nice! now we have a house type that we can use in our code.

Type Lookups

Let’s say we want to write a function that we pass in an object and key to get a value:

function getProp<T>(obj: T, key: string) {
return obj[key];
}

The problem with this is typescript can’t figure out the returned value, it will be a type of any and we don’t want that. Typescript have a way to solve this

Let’s stick with the house object and build upon it. Typescript has another operator keyof. it takes an object type and produces a string or numeric literal union of its keys. In other word, it'll give us a type with the possible properties for our object.

type HouseKeys = keyof House; // "id" | "address"| "members"

Now we can use the same technique in our function to constraint the type P to only use keys of T

function getProp<T, P extends keyof T>(obj: T, key: P) {
return obj[key];
}

We can pass T[P] as returned type but typescript is clever enough to figure that out. Now our returned value type, our key is also typed and we can get sweet IntelliSense as a bonus.

2020

Six months of Typescript

20 Jul