Variant schema works but TypeScript says there's something wrong #269
-
Can anyone tell me what's the problem here? https://stackblitz.com/edit/typescript-pc279k?file=index.ts If you look at this example, I'm validating prefecture and cities in Japan. My variant code works, but TypeScript says there's a problem and I think because of this error, I can't use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I think the problem here is that const locations = [
{ pref: '北海道', city: '札幌市' },
{ pref: '北海道', city: '函館市' },
// ...
] as const;
type LocationItem = ObjectSchema<{
pref: LiteralSchema<(typeof locations)[number]['pref']>;
city: LiteralSchema<(typeof locations)[number]['city']>;
}>;
const locationsArray = locations.map((l) =>
object({ pref: literal(l.pref), city: literal(l.city) })
) as [LocationItem, LocationItem, ...LocationItem[]];
export const LocationSchema = variant('pref', locationsArray); Or const locations = [
{ pref: '北海道', city: '札幌市' },
{ pref: '北海道', city: '函館市' },
// ...
] as const;
const locationsArray = locations.map((l) =>
object({ pref: literal(l.pref), city: literal(l.city) })
);
type LocationItem = (typeof locationsArray)[number];
export const LocationSchema = variant(
'pref',
locationsArray as [LocationItem, LocationItem, ...LocationItem[]]
); |
Beta Was this translation helpful? Give feedback.
This doesn't work how I thought it would. Since the type is "pref",
variant
assumes there's only onepref
, right? So only the firstpref
/city
pair is considered valid.This should actually be some sort of union:
[{pref: "a", city: 1}, {pref: "a", city: 2}, [{pref: "b", city: 3} /* ... */]