skip to Main Content

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

2

Answers


  1. I believe your await is operating against the array access and not the call to client.json.get. I was able to get similar issue from JavaScript and resolved it by calling:

    let results = await client.json.get('keyname', { path: '$.path'});
    return results[0];
    
    Login or Signup to reply.
  2. async function getSomeData(): Promise<returnObject[]> {
      return await client.json.get('keyname', { path: '$.path'}) as unknown as returnObject[]
    }
    

    Obviously you need to be sure that what you actually get from client.json.get(...) is of type Promise<returnObject[]> since this is essentially discarding the type of the return value and then casting it to what you want.

    It’s not the prettiest solution, but in my experience the typings in @redis/json aren’t the greatest.

    Hope this helps 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search