-
I've simplified the code for the readability. Below is the Typescript code that I want to migrate to Typebox syntax. interface Dictionary {
A: { count: number };
B: { type: string };
C: null;
}
type Base<K extends keyof Dictionary> = {
category: K;
data: Dictionary[K];
};
// Create the union of all variants:
type MergedBase = {
[K in keyof Dictionary]: Base<K>;
}[keyof Dictionary];
// now I can write type safe.
const base_A: MergedBase = {
category: 'A',
data: { count: 3 }
};
const base_C: MergedBase = {
category: 'C',
data: null
};
// This will error because for category 'B' data must be { type: string }
const base_B: MergedBase = {
category: 'B',
data: null
}; below is my work but I'm having a hard time finishing it. const dictionary = Type.Object({
A: Type.Object({
count: Type.Number(),
}),
C: Type.Null(),
});
const mapped = Type.Mapped(Type.KeyOf(dictionary), (K) => Type.Index(dictionary, K));
const key = Type.KeyOf(dictionary);
const base = <T extends typeof key>(T: T) =>
Type.Object({
category: T,
data: Type.Index(mapped, T),
}); Thank you. |
Beta Was this translation helpful? Give feedback.
Answered by
intaek-h
Feb 14, 2025
Replies: 1 comment 1 reply
-
I didn't know Typebox has workbench! I solved this there and want to thank the contributors for their works. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
intaek-h
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't know Typebox has workbench! I solved this there and want to thank the contributors for their works.
sharing the workbench link for the solution.