arktypea
arktype17mo ago
francis

Are there examples of how to create mapped types?

e.g. a { [K in <SomeOtherType>]: SomeValueType } type, where SomeValueType is either a static type or is computed from K.

I currently have a very basic setup where I have:
type MappedEnum<T extends string> = { readonly [K in T]: T };

const kitTypes = ["test_only", "test_self_serve", "test_guided_audit"];
const kitTypeValidator = type("===", ...kitTypes);
export type KitType = typeof kitTypeValidator.infer;
export const KitType = {
  test_only: "test_only",
  test_self_serve: "test_self_serve",
  test_guided_audit: "test_guided_audit",
} as const satisfies MappedEnum<KitType>;

This pattern allows me to generate, from a string array, a validator for an element in that array, a type for an element of the resulting string union type, and a type for a runtime object that lets me access the values analogous to an enum. And it's great!

My question is, I have the following type definition:
type KitCounts = { [K in KitType]?: number };

Is there a way to write an ArkType function that will generate a validator for this type (and the type definition itself), given the kitTypes array?
My initial attempt is:
const kitCountsValidator = type(
  Object.fromEntries(kitType.enumValues.map((k) => [`${k}?`, "number"])),
);

Obviously, this doesn't work, since the type information is completely lost. It actually works fine at runtime but the type is useless. Is there a way to do this without writing it out explicitly? (I have 5+ other enums that I'd like to process in a similar way)
Was this page helpful?