Below is the implementation of a helper class that generates a hash:
export default class PageUtil {
private size: number;
private step: PageUtilStep;
private cursor: unknown[] | undefined;
public constructor(size: number, step: PageUtilStep, cursor?: unknown[]) {
this.size = size;
this.step = step;
this.cursor = cursor;
}
public createHash(): string {
const json = JSON.stringify([this.size, this.step, this.cursor]);
return createHash("sha1").update(json).digest("hex");
}
}
type PageUtilStep = "backward" | "forward";
The following code snippet is where I encounter a TypeScript error at the return statement:
export default class TattooLoader {
private artistCache: Record<string, DataLoader<number, TattooEntity[]>>;
public constructor() {
this.artistCache = {};
}
public async fillArtist(artist: number, pageUtil: PageUtil): Promise<TattooEntity[]> {
const hash = pageUtil.createHash();
if (!this.artistCache[hash]) {
this.artistCache[hash] = new DataLoader(async (artists) => this.batchArtists(artists, pageUtil));
}
return this.artistCache[hash].load(artist);
}
private async batchArtists(artists: readonly number[], pageUtil: PageUtil): Promise<TattooEntity[][]> {
...
}
}
I am puzzled by why I receive this error even after checking if this.artistCache[hash]
is undefined
and creating it when needed.
When I tried to make the code more specific by testing for undefined before accessing it, the same error persisted:
public async fillArtist(artist: number, pageUtil: PageUtil): Promise<TattooEntity[]> {
const hash = pageUtil.createHash();
if (this.artistCache[hash]) {
return this.artistCache[hash].load(artist);
}
this.artistCache[hash] = new DataLoader(async (artists) => this.batchArtists(artists, pageUtil));
return this.artistCache[hash].load(artist);
}