Z
Zod•15mo ago
David Tejada

David Tejada - Hi. I have the following functio...

Hi. I have the following function which I have simplified for the example. The type Storage is inferred from the zod object zStorage. I would like to know why the type assertion is necessary here. Shouldn't the return type be inferred automatically when using parse?
export async function retrieve<T extends keyof Storage>(
key: T,
): Promise<Storage[T]> {
const retrieved = await browser.storage.local.get(key);

return zStorage.shape[key].parse(retrieved) as Storage[T];
}
export async function retrieve<T extends keyof Storage>(
key: T,
): Promise<Storage[T]> {
const retrieved = await browser.storage.local.get(key);

return zStorage.shape[key].parse(retrieved) as Storage[T];
}
Solution:
yea sorry you would indeed need a generic for that
Jump to solution
9 Replies
janglad
janglad•15mo ago
I assume you want something like this?
const zStorage = z.object({test: z.string(), test2: z.number()})
const browser : any = {};

type possibleKeys = "test" | "test2"

export async function retrieve(
key : possibleKeys,
) {
const retrieved = await browser.storage.local.get(key);

return zStorage.shape[key].parse(retrieved);
}
const zStorage = z.object({test: z.string(), test2: z.number()})
const browser : any = {};

type possibleKeys = "test" | "test2"

export async function retrieve(
key : possibleKeys,
) {
const retrieved = await browser.storage.local.get(key);

return zStorage.shape[key].parse(retrieved);
}
No description
janglad
janglad•15mo ago
the issue right now is that with your current setup key could be anything, including a non existing key
David Tejada
David TejadaOP•15mo ago
Why do you say it could be anything? It can only be one of the keys in Storage as it is typed
janglad
janglad•15mo ago
sorry kinda misread the intent of your code, didn't think about Storage being an external interface anyway, it can be anything since T extends keyof Storage but is not equal to it okay disregard once again lmfao
The type Storage is inferred from the zod object zStorage.
sorry had very little sleep KEKW anyway point still stands, altho in this case just do unless I'm once again missing something 😅
type possibleKeys = keyof z.infer<typeof zStorage>
type possibleKeys = keyof z.infer<typeof zStorage>
David Tejada
David TejadaOP•15mo ago
No problem😀 I was about to try that approach This doesn't work. The problem is the return type of something like await retrieve("test") is not string but string | number. The way I have done it works for me but I don't know if there is a cleaner way.
janglad
janglad•15mo ago
oohh wait sorry yes I'm starting to get around to what you were trying to do KEKW
David Tejada
David TejadaOP•15mo ago
I wanted to know if there is a way to avoid the type assertion
Solution
janglad
janglad•15mo ago
yea sorry you would indeed need a generic for that
David Tejada
David TejadaOP•15mo ago
Yeah, makes sense. Thanks

Did you find this page helpful?