Expression Variable Fix for Compiled Records (#403)

This commit is contained in:
sinclairzx81
2023-04-21 21:43:21 +09:00
committed by GitHub
parent 9e71365ed6
commit f8e50286d7
4 changed files with 21 additions and 5 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@sinclair/typebox",
"version": "0.28.1",
"version": "0.28.2",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@sinclair/typebox",
"version": "0.28.1",
"version": "0.28.2",
"license": "MIT",
"devDependencies": {
"@sinclair/hammer": "^0.17.1",

View File

@@ -1,6 +1,6 @@
{
"name": "@sinclair/typebox",
"version": "0.28.1",
"version": "0.28.2",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
"keywords": [
"typescript",

View File

@@ -248,7 +248,6 @@ export namespace TypeCompiler {
if (IsNumber(schema.minimum)) yield `${value} >= ${schema.minimum}`
if (IsNumber(schema.maximum)) yield `${value} <= ${schema.maximum}`
}
function* Object(schema: Types.TObject, references: Types.TSchema[], value: string): IterableIterator<string> {
yield IsObjectCheck(value)
if (IsNumber(schema.minProperties)) yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`
@@ -288,7 +287,7 @@ export namespace TypeCompiler {
if (IsNumber(schema.maxProperties)) yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`
const [patternKey, patternSchema] = globalThis.Object.entries(schema.patternProperties)[0]
const local = PushLocal(`new RegExp(/${patternKey}/)`)
const check1 = CreateExpression(patternSchema, references, value)
const check1 = CreateExpression(patternSchema, references, 'value')
const check2 = Types.TypeGuard.TSchema(schema.additionalProperties) ? CreateExpression(schema.additionalProperties, references, value) : schema.additionalProperties === false ? 'false' : 'true'
const expression = `(${local}.test(key) ? ${check1} : ${check2})`
yield `(Object.entries(${value}).every(([key, value]) => ${expression}))`

View File

@@ -2,6 +2,23 @@ import { Type } from '@sinclair/typebox'
import { Ok, Fail } from './validate'
describe('type/compiler/Record', () => {
// -------------------------------------------------------------
// Issues
// -------------------------------------------------------------
it('Issue: https://github.com/sinclairzx81/typebox/issues/402', () => {
const T = Type.Object({
foo: Type.Object({
bar: Type.Record(Type.String(), Type.Number()),
}),
})
Ok(T, { foo: { bar: { x: 42 } } })
Ok(T, { foo: { bar: {} } })
Fail(T, { foo: { bar: { x: '42' } } })
Fail(T, { foo: { bar: [] } })
Fail(T, { foo: {} })
Fail(T, { foo: [] })
Fail(T, {})
})
// -------------------------------------------------------------
// TypeBox Only: Date and Record
// -------------------------------------------------------------