Repository navigation
Schema type with optional properties #1228
Replies: 1 comment
|
For the import {
Type,
type Static,
type TString,
type TNumber,
type TBoolean,
} from '@sinclair/typebox';
type AllowedProperties = {
foo: TString;
bar: TNumber;
baz: TBoolean;
};
const properties = {
foo: Type.String(),
baz: Type.Boolean(),
} satisfies Partial<AllowedProperties>;
const schema = Type.Object(properties);
type Data = Static<typeof schema>; // { foo: string; baz: boolean }
For a library API that accepts these property definitions and allows additional schema properties, a generic factory preserves the same inference: import type { TProperties } from '@sinclair/typebox';
function defineSchema<P extends TProperties & Partial<AllowedProperties>>(
properties: P,
) {
return Type.Object(properties);
}
const custom = defineSchema({ foo: Type.String(), baz: Type.Boolean() });
// defineSchema({ foo: Type.Number() }); // compile-time errorThere are two different meanings of optional here. The above permits developers to leave a property out of the schema definition. Properties they do include are still required in validated data. If the data fields themselves should also be optional, use Checked with TypeScript's |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi, I'm coding a library where developers will be able to define their own schema, which should extend a certain type.
Every property of this type must be optional.
Is this possible with Typebox ? How can I achieve this ?
I tried this :
But I get this error
All reactions