How to create typebox type that is the same as typescript typeof MyEnum
?
#509
-
I have the following enum:
How to create a typebox type which represents the enum content? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@meightythree Hi, You can pass a enum MyEnum {
first = 'first',
second = 'second',
}
const T = Type.Enum(MyEnum) // const T = {
// anyOf: [{
// type: 'string',
// const: 'first',
// }, {
// type: 'string',
// const: 'second',
// }
// ],
// }
type T = Static<typeof T> // type T = MyEnum
function test(value: T) {}
test(MyEnum.first) // ok - matches anyOf variant
test(MyEnum.second) // ok - matches anyOf variant
test(MyEnum) // fail - not a anyOf variant In the above, take note of the third test case. Note that because TypeBox encodes Hope this helps |
Beta Was this translation helpful? Give feedback.
@meightythree Hi,
You can pass a
enum
intoType.Enum
which will create a union (anyOf) schema. You can then useStatic<typeof T>
which will return the original enum type (as it would be understood by TypeScript)