sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.65k stars 150 forks source link

Should add option to remove redundant prop in Convert() #830

Closed woody146 closed 3 months ago

woody146 commented 3 months ago

Current

Convert(Type.Object({}), {a: 'string'})
=> {a: 'string'}

Should add option (such as strict: boolean)

Convert(Type.Object({}), {a: 'string'}, {strict: true})
=> {}
sinclairzx81 commented 3 months ago

@woody146 Hi,

The Convert function only coerces data if a conversion is possible, but it doesn't subtract from the value, and doesn't remove additional properties. To remove excess properties, use the Clean function which will remove any property or element from the value which doesn't have a exact definition derived from the schematic.

import { Clean, Convert } from '@sinclair/typebox/value'

function Process(schema: TSchema, value: unknown): unknown {
  const converted = Convert(schema, value)
  return Clean(schema, converted)
}

Hope this helps. Will close off the issue for now, but if you have any follow up questions, feel free to reply on this thread. Cheers! S