-
Notifications
You must be signed in to change notification settings - Fork 170
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TSchema can't infer TMappedKey #1172
Comments
@intaek-h Hi, This is a general limitation with Mapped. You can resolve by implementing the TS types slightly differently interface Dictionary {
A: { count: number };
B: { type: string };
C: null;
}
// Update: Base<...> accepts exterior Category and Data parameters
type Base<Category extends PropertyKey, Data extends unknown> = {
category: Category;
data: Data;
}
// Update: Pass Category + Data as parameter
type BaseMapped = {
[Category in keyof Dictionary]: Base<Category, Dictionary[Category]>;
}
// type MergedBase = Base<"A"> | Base<"B"> | Base<"C">
type MergedBase = BaseMapped[keyof Dictionary] Which generates the following import { Type, Static, TSchema } from '@sinclair/typebox'
type Dictionary = Static<typeof Dictionary>
const Dictionary = Type.Object({
A: Type.Object({
count: Type.Number()
}),
B: Type.Object({
type: Type.String()
}),
C: Type.Null()
})
type Base<Category extends TSchema, Data extends TSchema> = Static<
ReturnType<typeof Base<Category, Data>>
>
const Base = <Category extends TSchema, Data extends TSchema>(
Category: Category,
Data: Data
) =>
Type.Object({
category: Category,
data: Data
})
type BaseMapped = Static<typeof BaseMapped>
const BaseMapped = Type.Mapped(Type.KeyOf(Dictionary), (Category) =>
Base(Category, Type.Index(Dictionary, Category))
)
type MergedBase = Static<typeof MergedBase>
const MergedBase = Type.Index(BaseMapped, Type.KeyOf(Dictionary)) Just be mindful that while the Workbench does its best to map TS types, it may not always generate a direct translation to TypeBox. Achieving 1-1 mapping is an ongoing work in progress, but mostly if you can simplify TS types things generally map easier. Unfortunately, implementing mapped types at runtime / statically requires an exceptional amount of complexity to achieve, there may be limitations here and there. Hope this helps |
@sinclairzx81 Thank you very much. I love your work! |
I have a typescript code I want to migrate to Typebox.
I tried Typebox workbench and it gave me this code, which is not equal to the original typescript type.
I've been into this for hours and I can't find the solution..
The text was updated successfully, but these errors were encountered: