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')
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With