Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cache type only takes unknown as key #56

Open
fregante opened this issue Dec 17, 2023 · 2 comments
Open

cache type only takes unknown as key #56

fregante opened this issue Dec 17, 2023 · 2 comments
Labels

Comments

@fregante
Copy link
Collaborator

I'm trying to write a local filesystem cache:

const fetchDocument = pMemoize(async (url: string): Promise<string> => {
	const request = await fetch(url, {
		headers: {
			Accept: 'text/html',
		},
	});
	return request.text();
}, {
	cache: {
		async get(url: string): Promise<string | undefined> {
			try {
				return await readFile(`./test/.cache/${filenamify(url)}.html`, 'utf8');
			} catch {
				return undefined;
			}
		},
		async set(url: string, contents: string): Promise<void> {
			await writeFile(`./test/.cache/${filenamify(url)}.html`, contents);
		},
		async has(url: string): Promise<boolean> {
			return Boolean(await this.get(url));
		}
	}
});

Every cache method is failing with:

Type '(url: string) => Promise<string | undefined>' is not assignable to type '(key: unknown) => string | Promise<string | undefined> | undefined'.
  Types of parameters 'url' and 'key' are incompatible.
    Type 'unknown' is not assignable to type 'string'.ts(2322)
@fregante fregante added the bug label Dec 17, 2023
@fregante
Copy link
Collaborator Author

Interestingly, if I move the cache to its own object it's fine…

import pMemoize from 'p-memoize';
import filenamify from 'filenamify';
import {writeFile, mkdir, unlink, readFile} from 'node:fs/promises';

const fsCache = {
	async get(path: string): Promise<string | undefined> {
		try {
			return await readFile(path, 'utf8');
		} catch {
			return undefined;
		}
	},
	async set(path: string, contents: string): Promise<void> {
		await writeFile(path, contents);
	},
	async has(path: string): Promise<boolean> {
		return Boolean(await this.get(path));
	},
	async delete(path: string): Promise<void> {
		await unlink(path);
	},
} as const;
const fetchDocument = pMemoize(async (url: string): Promise<string> => {
	const request = await fetch(url, {
		headers: {
			Accept: 'text/html',
		},
	});
	return request.text();
}, {
	cacheKey: ([url]) => `./test/.cache/${filenamify(url)}.html`,
	cache: fsCache,
});

@sindresorhus
Copy link
Owner

It seems to me like a TypeScript limitation. I looked into this today, but failed to find a solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants