sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.56k stars 148 forks source link

MaxLength on keys defining a Type.Record #864

Closed danieled-subbyx closed 2 months ago

danieled-subbyx commented 2 months ago

Hi,

Maybe i'm missing something but this type checking seems to not be respected

meta: Type.Record(Type.String({maxLength: 1}), Type.String())

Basically i can forward an object like without errors

{ "aaaaaa": 1 }

How can i check the length of the key in a record ?

Many thanks,

sinclairzx81 commented 2 months ago

@danieled-subbyx Hi,

It's not possible to pass a String maxLength for a Record Key, but you can pass a pattern. The following creates a Record type that accepts property keys with lengths no more than 8.

import { Type } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'

const T = Type.Record(Type.String({ pattern: '^.{0,8}$' }), Type.Number(), {
  additionalProperties: false // required
})

console.log(Value.Check(T, { '12345678': 1 }))  // true
console.log(Value.Check(T, { '123456789': 1 })) // false

Just be mindful that you will need to specify additionalProperties: false as passing keys with lengths > 10 would be interpreted as additional properties by validators. The additionalProperties false constraint ensures this is disallowed.

Hope this helps S

sinclairzx81 commented 2 months ago

@danieled-subbyx Heya

Will close this one off for now, but if you have any follow up questions, feel free to ping on this thread. Cheers S