Skip to content

Add a type generic to typescript build for document type #509

@Liam-Tait

Description

@Liam-Tait

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Add a generic Document to the build function, in particular when built with an build.ObjectSchema.

This can be done with in a non breaking way which defaults to the current approach.
Something like:

declare function build<Document extends object = object>(schema: build.ObjectSchema, options?: build.Options): (doc: Document) => string;

Motivation

This would add an additional layer of safety when in typescript when using the stringify function with data, ensuring all required fields are available.

For my particular use case, I am using typebox so my code would end up looking like:

const ExampleSchema = Type.Static(
  Type.Object({
    foo: Type.String(),
    bar: Type.String(),
  })
)
type Example = Static<typeof ExampleSchema>
const stringifyExample = fastJson<Example>(ExampleSchema)

Example

import fastJson from 'fast-json-stringify'

interface Example {
  foo: string
  bar: string
}

const schema = {
  title: 'Example Schema with required field',
  type: 'object',
  properties: {
    foo: { type: 'string' },
    bar: { type: 'string' }
  },
  required: ['foo', 'bar']
}

const stringify = fastJson<Example>(schema)

// This would be ok 
stringify({ foo: 'Foo', bar: 'Bar' })

// This would be error at compile time 
stringify({ foo: 'Foo' })

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions