I am currently working on a class that includes a protected map holding various values, along with a method to add new entries to this map.
class DataStorage {
protected readonly dataValues: Map<PropertyKey, number> = new Map();
public updateData(key: PropertyKey, value: number): void {
if (this.dataValues.has(key)) {
throw new Error('key already exists');
} else {
this.dataValues.set(key, value);
}
}
}
Is there a way to set up types for this class and method so that if a key is added which already exists in the map, it would trigger a type error during compilation rather than throwing an error at runtime? I know it's possible to handle this with an Error message, but I'm curious about achieving this check using TypeScript compiler.
const storage = new DataStorage();
storage.updateData('apple', 4); // valid
storage.updateData('banana', 5); // valid
storage.updateData('apple', 6); // invalid - 'apple' already exists!