When z.infer
a Record
with Brand
as a key, it becomes a Partial Record.
#2069
-
When With defining a Record type normally: import { z } from "zod";
const zodKey = z.string().brand("zodKey");
type ZodKey = z.infer<typeof zodKey>;
type ZodRecord = Record<ZodKey, number>;
// type ZodRecord = {
// [x: string & z.BRAND<"zodKey">]: number;
// } With defining a Record type with import { z } from "zod";
const zodKey = z.string().brand("zodKey");
const zodRecord = z.record(zodKey, z.number());
type ZodRecord = z.infer<typeof zodRecord>;
// type ZodRecord = {
// [x: string & z.BRAND<"zodKey">]: number | undefined;
// } It has |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 11 replies
-
Technically in TypeScript, when you use const partialRecord: Record<string, string> = {} // no errors I'm not sure why the If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
I followed the discussion. Here Here I thought it was more intuitive to not make it a |
Beta Was this translation helpful? Give feedback.
-
Is this what you are looking for? const zodKey = z.string().brand( "zodKey" )
// with TypeScript
type ZodKey = z.infer<typeof zodKey>
type ZodRecord1 = Record<ZodKey, number | undefined>
// with Zod (will be Partial)
const zodRecord = z.record( zodKey, z.number() )
type ZodRecord2 = z.infer<typeof zodRecord>
const record2: ZodRecord2 = {}
const record1: ZodRecord1 = record2 // no error, yay! If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
It seems the problem is caused by this code: Lines 3061 to 3069 in 981af65 If it were changed to: |
Beta Was this translation helpful? Give feedback.
-
I really can't get my head around the export declare type RecordType<K extends string | number | symbol, V> = [
string
] extends [K] ? Record<K, V> : [number] extends [K] ? Record<K, V> : [symbol] extends [K] ? Record<K, V> : [BRAND<string | number | symbol>] extends [K] ? Record<K, V> : Partial<Record<K, V>>; Shouldn't it rather be export declare type RecordType<K extends string | number | symbol, V> = [
K
] extends [string] ? Record<K, V> : [K] extends [number] ? Record<K, V> : [K] extends [symbol] ? Record<K, V> : [K] extends [BRAND<string | number | symbol>] ? Record<K, V> : Partial<Record<K, V>>; WDYT? I also don't quite get how we could have a |
Beta Was this translation helpful? Give feedback.
It seems the problem is caused by this code:
zod/src/types.ts
Lines 3061 to 3069 in 981af65
If it were changed to:
[K] extends [string]
, it might work for you.However, I'm not sure if that will be a breaking change for other users.