ioredis icon indicating copy to clipboard operation
ioredis copied to clipboard

Specify types on read and write operations

Open bacloud22 opened this issue 2 years ago • 3 comments

When I simply run an operation that reads or writes, for instance, get & set/ push can I simply provide what is expected through generic types ?

Like redis.get<ClassA>(key)
or

const objs: ClassB[] =[{}] // example
const redis.lpush<ClassB>(key, objs)

Thanks a lot

bacloud22 avatar Jun 05 '23 11:06 bacloud22

It doesn't make sense to support generics as lpush always accept strings. What's your use case?

luin avatar Jun 05 '23 13:06 luin

Sorry, my bad you are right. But what about a function that serialize and de- serialize strings and use the generic version of the API. I'm sure in most cases people do JSON.stringify(obj) before insertion and JSON.parse(str) after getting values.

I myself keep doing this.

bacloud22 avatar Jun 11 '23 18:06 bacloud22

I think it would make more sense in this situation:

interface UserProfile {
  id: string;
  username: string;
}

const userId = "ab4dfe5"
const user = await redis.hgetall<UserProfile>(userId)
//    ^? {} | UserProfile

const user = await redis.hgetall(userId)
//    ^? {} | Record<string, string>

However it wouldn't be feasible as number fields are returned as strings so unless a serializer is provided this can not happen

noook avatar Mar 06 '24 17:03 noook