How to make only some props optional #1125
-
I want to derive a new Schema where some props are optional and came up with the following solution (drizzle-typebox): import {createSelectSchema} from 'drizzle-typebox';
export const filesTbl = table(
'files',
{
id: integer().primaryKey({autoIncrement: true}),
...tstamps,
name: text({length: 255}).notNull(),
contentType: text({length: 255}).notNull().default('application/octet-stream'),
size: integer().notNull()
},
);
export const filesSelectSchema = createSelectSchema(filesTbl);
export const filesInsertSchema = Type.Object({
...Type.Omit(filesSelectSchema, ['id', 'created_at', 'updated_at', 'contentType']).properties,
contentType: Type.Optional(filesSelectSchema.properties.contentType), // We have a default value for contentType
}); So I thought about how this could be expressed in a more intuitive way like Is there a better way to do this? What do you think about extending the Optional() method? Greets |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@psi-4ward Hi, Try the following import { Type } from '@sinclair/typebox'
// ----------------------------------------------------------------
// TypeScript
// ----------------------------------------------------------------
type Composite<T> = {[K in keyof T]: T[K]} & {} // replicate TB composite
type FileSelect = {
id: string,
created_at: number
updated_at: number
contentType: string
filename: string
description: string
}
type FileInsert = Composite<
Omit<FileSelect, 'id' | 'created_at' | 'updated_at' | 'contentType'> &
Partial<Pick<FileSelect, 'contentType'>>
>
// ----------------------------------------------------------------
// TypeBox
// ----------------------------------------------------------------
const FilesSelect = Type.Object({
id: Type.String(),
created_at: Type.Number(),
updated_at: Type.Number(),
contentType: Type.String(),
filename: Type.String(),
description: Type.String()
})
const FilesInsert = Type.Composite([
Type.Omit(FilesSelect, ['id', 'created_at', 'updated_at', 'contentType']),
Type.Partial(Type.Pick(FilesSelect, ['contentType'])),
]) It is generally recommended to construct types using the TB API where possible. TypeBox is mostly aligned to how you would construct the same type using TypeScript. While it is possible construct properties using the Hope this helps! |
Beta Was this translation helpful? Give feedback.
@psi-4ward Hi, Try the following
TypeScript Link Here