I'm having an issue correctly typing the redis node package correctly. As an example of the base code for a simple JSON.GET
import * as redis from 'redis';
const client = redis.createClient();
async function getSomeData() {
return await client.json.get('keyname', { path: '$.path'})
}
async functions return a Promise, and in this example, I expect the data returned from redis to be an array of objects, something like
type returnObject = {
key1: string;
key2: string;
}
What I'm struggling with is how to only return the first object from that returned array, if I try:
async function getSomeData() {
return await client.json.get('keyname', { path: '$.path'})[0]
}
I get the following error in vscode:
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Promise<string | number | boolean | Date | (string | number | boolean | Date | (string | number | boolean | Date | (string | number | boolean | Date | (string | ... 5 more ... | null)[] | { ...; } | null)[] | { ...; } | null)[] | { ...; } | null)[] | { ...; } | null>'.
and therefore, understandably, I get a similar error stating the same is not assignable to type returnObject if I try something like
async function getSomeData(): Promise<returnObject[]> {
return await client.json.get('keyname', { path: '$.path'})
}
I think this type is coming from the RedisJSON type from the @node-redis package, but either way, I'm unclear on how to resolve this. The only way I can get close to something that works is to use a helper function that assigns the result of getSomeData to an any type, but that defeats the point of using TypeScript. Can anyone point me in the direction of how you should go about correctly typing async functions that use the new RedisJSON methods such that the results can be worked with? Thank you
Edit: for clarity, the package I'm using is https://www.npmjs.com/package/redis