Type Parameters and Enums Just Got Beta

Amyas Merivale
Skiller Whale
Published in
2 min readFeb 1, 2023
Two betta fish. I work at Skiller Whale, so I’m contractually obliged to include fish puns in everything I do.

I was excited by last week’s announcement of the TypeScript 5.0 beta. Apart from the compilation speed improvements that I’m keen to try out, I was most struck by the addition of const type parameters and the improvement to enums.

Const Type Parameters

These are going to make working with generics much simpler when you care about literal types.

In a nutshell:

// before:
const exclude = <Element>(array1: Element[], array2: Element[]): Element[] =>
array1.filter((element) => !array2.includes(element))

const drinks = exclude(["beer", "wine", "gin"], ["wine"])
// inferred type of drinks is string[]

// v5.0:
const exclude = <const Element>(array1: Element[], array2: Element[]): Element[] =>
array1.filter((element) => !array2.includes(element))

const drinks = exclude(["beer", "wine", "gin"], ["wine"])
// inferred type of drinks is ("beer" | "wine" | "gin")[]

There were ways to get the compiler to infer the narrower type before, but they weren’t pleasant. Now it’s a breeze. 😊

All Enums are Union Enums

This is basically a fancy way of saying that numeric enums are now (almost completely) type safe. TypeScript enums have been quite controversial. Personally I like them (in the right places), but the one thing that always really bugged me was the fact that you can assign any number to a variable with a numeric enum type, even if it isn’t one of the enum’s values. This is soon to be a thing of the past:

enum Status {
Off, // 0
On, // 1
}

// before:
const status: Status = 42 // no error! what?

// v5.0:
const status: Status = 42 /*
~~~~~~
Type '42' is not assignable to type 'Status'. */

That’s more like it. Careful though, it will still let you do silly arithmetic:

const status: Status = 14 * 3 // still no error :(

Even so, this is a big improvement.

--

--