Tuesday, November 21, 2017

Typescript is fun

I recently went from programming on Java for almost 20 years to programming exclusively in Typescript and I like it.

Typescript is a super set of Javascript. It is essentially a typing system built on top of Javascript and it works amazingly well. When I first started programming in it I expect it to be a dancing bear, and from one perspective it sort of is, but man does this bear dance.

The way to think about Typescript is it makes Javascript scale. It's not really trying to be its own language as much as a set of tools that allow you to take existing Javascript code and add some typing sanity onto it. What makes it work is a combination of crazy good type inference and a sort of strong duck typing. So if you have something like this:

interface Person {
 String name;
 int age;
}

interface Monkey {
 String name;
 int age;
}


you can do this:
Person p = new MonkeyInstance();

or this:

Person p = { name: "Steve", age: 12 };
Monkey m = p;

and it doesn't care. So long as the interfaces are compatible you can assign it and it's all good. Java can't do this because Java is tracking types at the byte code level. A monkey and person are two different types that just happen to have the same properties. For Typescript having the same properties is what defines a type.

(Java does allow this sort of assignment in an around about fashion with functions. For instance, you can pass any method that takes a value and returns a value to a method expecting a Function. But it only works with functions, not objects)

Typescript also implements an idea I've wanted to see implemented for a long time. Nullable as a type!

In Java, we've started to use "Optional" instead of null because it makes the optional nature of the value part of the type. But, what if the language did it for you? Well Typescript does. Basically, you can't do this:

Person p = null;

You have to express that p might be null like this:

Person | null p = null;

Trying to do this using Java syntax gets confusing but the idea is that p might be a Person or it might be a null. Like using Optional, it makes the compiler track that a value might be optional, but unlike optional it's built in. The same multi-type trick works with any types:

Person | Exception p = findPerson();

p might be an Exception type or a Person and you'd need to do some additional work to work out what p is.

You can append however many you want:

Person | Exception | null p = findPerson();

In java you can do this with exception catch blocks, but nowhere else:

try {
 stuff();
} catch (NullPointerException | IOExecption | SqlException ex) {
 // ...
}

Here's a video of the inventor of Typescript explaining how Typescript deals with null.


2 comments:

Vijay Sharma said...

Hey Andrew! Ever try Kotlin? I had the same feeling after moving away from java.

Andrew said...

I hadn't heard of Kotlin. I'll take a look.