Skip to content

Commit f6194c6

Browse files
authored
fix: support generic types for kv.get (#14494)
When getting values from the KV store, it is currently not possible to type the return value without using assertions, etc. This is because `payload.kv.get()` does not support generic types, forcing you to use a workaround like this: ```ts const value = await payload.kv.get('my-key') as MyValue // or const value: MyValue = await payload.kv.get('my-key') // and so on... ``` Now, you can use generics and the return type will be applied automatically: ```ts const value = await payload.kv.get<MyValue>('my-key') // `value` is now typed as `MyValue` ```
1 parent 76ba2df commit f6194c6

File tree

4 files changed

+7
-7
lines changed

4 files changed

+7
-7
lines changed

packages/kv-redis/src/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ export class RedisKVAdapter implements KVAdapter {
2424
await this.redisClient.del(`${this.keyPrefix}${key}`)
2525
}
2626

27-
async get(key: string): Promise<KVStoreValue | null> {
27+
async get<T extends KVStoreValue>(key: string): Promise<null | T> {
2828
const data = await this.redisClient.get(`${this.keyPrefix}${key}`)
2929

3030
if (data === null) {
31-
return data
31+
return null
3232
}
3333

3434
return JSON.parse(data)

packages/payload/src/kv/adapters/DatabaseKVAdapter.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ export class DatabaseKVAdapter implements KVAdapter {
2727
})
2828
}
2929

30-
async get(key: string): Promise<KVStoreValue | null> {
30+
async get<T extends KVStoreValue>(key: string): Promise<null | T> {
3131
const doc = await this.payload.db.findOne<{
32-
data: KVStoreValue
32+
data: T
3333
id: number | string
3434
}>({
3535
collection: this.collectionSlug,

packages/payload/src/kv/adapters/InMemoryKVAdapter.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ export class InMemoryKVAdapter implements KVAdapter {
1212
this.store.delete(key)
1313
}
1414

15-
async get(key: string): Promise<KVStoreValue | null> {
16-
const value = this.store.get(key)
15+
async get<T extends KVStoreValue>(key: string): Promise<null | T> {
16+
const value = this.store.get(key) as T | undefined
1717

1818
if (typeof value === 'undefined') {
1919
return null

packages/payload/src/kv/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ export interface KVAdapter {
2222
* @param key - The key to look up.
2323
* @returns A promise that resolves to the value, or `null` if not found.
2424
*/
25-
get(key: string): Promise<KVStoreValue | null>
25+
get<T extends KVStoreValue>(key: string): Promise<null | T>
2626

2727
/**
2828
* Checks if a key exists in the store.

0 commit comments

Comments
 (0)