samedi 28 novembre 2020

How to create type safe "Recursive" type?

I want to create typed tree sctructure, passing root and child nodes schemas. I expect required properties to be required and optional not to be required, according to schemas, as it must be. However my type test doesn't pass. Here's my piece of code:

type TypedTree<TRootSchema, TChildSchema = TRootSchema> =
  {
    [K in keyof TRootSchema]: TRootSchema[K]
  } | {
    [key: string]: TypedTree<TChildSchema>
  }

const $typeTest = <T>(v: T) => v

// @ts-expect-error Required properies must be present
$typeTest<TypedTree<{ a: number }>>({ })
// 👆 It fails

Aucun commentaire:

Enregistrer un commentaire