Effect CommunityEC
Effect Community2y ago
18 replies
spaethnl

Issue with Recursive Schema Initialization in TypeScript

What is going wrong with this recursive schema? Isn't this what S.suspend() is supposed to avoid?

// ReferenceError: Cannot access 'MySchema' before initialization
     12| type $MySchema = S.Schema<IMySchema>
     13| const MySchemaModel = { parent: S.optional(S.suspend((): $MySchema => MySchema)) } as const
       |                                                                       ^
     14| const MySchemaAnnotations = {}
     15| export class MySchema extends MyBaseSchema.extend<MySchema>('MySchema')(MySchemaModel, MySchemaAnnotations) {}


import * as S from '@effect/schema/Schema'
interface IMySchema { readonly parent?: IMySchema | undefined }
type $MySchema = S.Schema<IMySchema>
const MySchemaModel = { parent: S.optional(S.suspend((): $MySchema => MySchema)) } as const
const MySchemaAnnotations = {}
export class MySchema extends S.Class<MySchema>('MySchema')(MySchemaModel, MySchemaAnnotations) {}


import { describe, expect, it } from 'vitest'

describe('MySchema', () => {
  it('create MySchema', () => {
    const mySchema = new MySchema({ id: 'my-id' })
  })
})
Was this page helpful?