I'm currently working on developing a generic repository in TypeScript that involves serialization and deserialization using localStorage.
While researching, I have come across several relevant discussions regarding the use of new()
in ts. However, most examples are filled with placeholders like foos, bars, and bazes, making it challenging to find a concrete demonstration of this concept. In particular, I am struggling to find an example demonstrating how to create a new instance within a generic class (as opposed to assuming that the type is already known).
Let's start with a simple "Dog" entity:
interface IEntity { }
class Dog implements IEntity {
constructor(json: string); // invoked during deserialization
constructor(name: string, age: number);
constructor(jsonOrName: string, age?: number) { /* implementation... */ }
name: string;
age: number;
toJSON() { // utilized for serialization (via JSON.stringify)
//...
}
}
We also have a repository responsible for handling serialization and deserialization to/from localStorage.
class Repository<T extends IEntity> {
constructor(private key: string) { }
read(): T | null {
const storedData = localStorage.getItem(this.key);
if (!storedData) return null;
const value = JSON.parse(storedData);
return new T(value); // <----------- in need of guidance here
}
write(value: T): void {
localStorage.setItem(this.key, JSON.stringify(value));
}
}
The intended usage scenario is as follows:
const dogRepository = new Repository<Dog>("dog");
const retrievedDog = dogRepository.read();
if (retrievedDog) console.log(retrievedDog.name);