sinclairzx81 / typebox

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

Strict error: Unknown type #748

Closed liyofx closed 7 months ago

liyofx commented 7 months ago
var T = Type.Object({
  name: Type.String(),
  age: Type.Number(),
});
const strictObjectType = Type.Strict(T);
const validObject = { name: 'John', age: 30 };
const isValid = Value.Check(strictObjectType, validObject);
expect(isValid).toBeTrue();
➜  prisma-zod-generator git:(typebox) ✗ bun test
bun test v1.0.25 (a8ff7be6)

test/generator.test.ts:
» test
1 | /** The base Error type thrown for all TypeBox exceptions  */
2 | export class TypeBoxError extends Error {
3 |     constructor(message) {
4 |         super(message);
            ^
error: Unknown type
      at new TypeBoxError (/Users/z/Documents/web/prisma-zod-generator/node_modules/@sinclair/typebox/build/import/type/error/error.mjs:4:9)
      at new ValueCheckUnknownTypeError (/Users/z/Documents/web/prisma-zod-generator/node_modules/@sinclair/typebox/build/import/value/check/check.mjs:24:9)
      at Visit (/Users/z/Documents/web/prisma-zod-generator/node_modules/@sinclair/typebox/build/import/value/check/check.mjs:451:23)
      at /Users/z/Documents/web/prisma-zod-generator/test/generator.test.ts:32:21
✗ test [1.07ms]

 0 pass
 1 skip
 1 fail
Ran 2 tests across 1 files. [136.00ms]
➜  prisma-zod-generator git:(typebox) ✗ 
sinclairzx81 commented 7 months ago

@liyofx Hi,

This is expected. The Strict function discards all compositing symbols TypeBox uses to operate. Note that these symbols are used to compose schematics, differentiate between ambiguous static types, but are also used to type check. As such, calling Strict on a type will result in the type no longer being considered valid.

The Strict function was historically used to resolve issues in Ajv where unknown properties (i.e. these symbols) were flagged in Ajv strict mode as invalid. More recent versions of TypeBox use a different strategy that mitigates the need to Strict before use, so the function is largely kept around for backwards compatibility (notably for large early adopter projects which still use it for couple of things)

All this said, the Strict function shouldn't be used if working against TypeBox's compiler and value modules.

Hope this brings some insight! Cheers! S

sinclairzx81 commented 7 months ago

@liyofx Heya,

All things are working as expected here. Will close off this issue for now, but happy to field any additional questions you might have on this thread.

Cheers! S