sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.77k stars 152 forks source link

Value.Cast not working with an imported enum #790

Closed ItaiCovver closed 5 months ago

ItaiCovver commented 5 months ago

random-enum.ts

enum randomEnum {
  random = random,
};

test.ts

import { Value } from '@sinclair/typebox/value';
import { Type } from '@sinclair/typebox';
import { randomEnum } from './random-enum'

Value.Cast(Type.Object({enum: Type.Enum(randomEnum)}), {enum: 'random'});

This will throw a ValueCheck: Unknown type error. If the enum was defined in the same file then this works no problem

sinclairzx81 commented 5 months ago

@ItaiCovver Hi,

Have tested this and cannot replicate. This issue sounds like it may have something to do with either the toolchain your using (i.e. bundler, monorepo manager, etc) or you may have multiple versions of TypeBox installed (as a guess)

Here are some things you can try.....

1) Check you only have one version of TypeBox installed. Multiple versions may cause Unknown type errors due to conflicts with multiple defined symbols from different versions.

2) Check that the Type.Object value contains the appropriate symbols for Kind and Hint

Here's some test script.

import { Type } from '@sinclair/typebox';

export enum randomEnum { // try moving this to a separate file and testing again

  random = 'random'      // note that the value of enum variants can only be
};                       // number of string. The variable assignment in your
                         // example code may be a typo.

const T = Type.Object({enum: Type.Enum(randomEnum)})

console.log(T) // should print {
               //   type: 'object',
               //   properties: {
               //     enum: {
               //       const: 'random',
               //       type: 'string',
               //       [Symbol(TypeBox.Kind)]: 'Literal', // required
               //       [Symbol(TypeBox.Hint)]: 'Enum'     // required
               //     }
               //   },
               //   required: [ 'enum' ],
               //   [Symbol(TypeBox.Kind)]: 'Object'       // required
               // }

Note that the ValueCheck: Unknown type is caused by TypeBox not finding these symbols on the types you pass it. TypeBox uses these symbols as a safety guard before performing value ops. Also check that the types haven't been modified the type in someway (i.e. updated, deleted properties or values) as TypeBox is very strict about the structure of the schematics passed to it.

Let me know if this helps Cheers S

ItaiCovver commented 5 months ago

Found the issue. We were overriding Type.Enum to get it to work with OpenAPI https://github.com/sinclairzx81/typebox/issues/107#issuecomment-921959683. Later versions of TypeBox fixed this openAPI problem I presume so just had to get rid of it