Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a frozen set in TypeScript?

Tags:

typescript

Let's say I have a set of values that I don't want to be editable, like this:

// I don't want this to be editable.
const listenedKeys = new Set(['w', 'a', 's', 'd'])

// This should be fine.
const hasA = listenedKeys.has('a')

// I want this to give an error.
listenedKeys.add('r')

Can I "freeze" this set in TypeScript? How?

I've tried using the Readonly utility type, but that doesn't prevent me from modifying the set:

const listenedKeys: Readonly<Set<string>> = new Set(['w', 'a', 's', 'd'])

// No error here
listenedKeys.add('r')
like image 836
ChrisCrossCrash Avatar asked Sep 15 '25 16:09

ChrisCrossCrash


1 Answers

TypeScript already supports this type natively. It is called ReadonlySet and will do exactly what you want - you will not be allowed to modify the set once created

const listenedKeys: ReadonlySet<string> = readOnlySet(new Set(['w', 'a', 's', 'd']))

Playground Link

If you want to use implicit typing, you can create a small helper function that will serve only to switch the types:

const readonlySet = <T>(set: Set<T>): ReadonlySet<T> => set;

const listenedKeys = readonlySet(new Set(['w', 'a', 's', 'd']))

Playground Link

The type is defined in the es2015.collection.d.ts file alongside analogous types ReadonlyMap.

like image 127
VLAZ Avatar answered Sep 18 '25 11:09

VLAZ