typecheck.macro icon indicating copy to clipboard operation
typecheck.macro copied to clipboard

[feature request] define constraints at the type-level

Open ducaale opened this issue 3 years ago • 1 comments

Sometimes, I have a type A that might be used in other types. If I need to add constraints on that type, I would have to repeat those constraints every time I create a validator for a type that references type A.

type Url = string

type Video = {
  url: Url
  length: number
}

type Image = {
  url: Url
  width: number
  height: number
}

registerType('Video')
register('Image')

const imageValidator = createValidator<Image>(undefined, {
  constraints: {
    Url: x => x.startsWith('http://') // this can't be moved to an object or babel-macro will complain
  }
})

const videoValidator = createValidator<Video>(undefined, {
  constraints: {
    Url: x => x.startsWith('http://')
  }
})

It would be nice if one of the following was possible:

  • Type constraints can be defined when registering the corresponding type

    type Url = string
    
    type Video = {
      url: Url
      length: number
    }
    
    type Image = {
      url: Url
      width: number
      height: number
    }
    
    registerType('Url', x => x.startsWith('http://'))
    registerType('Video')
    register('Image')
    
    const x = createValidator<Image>()
    const x = createValidator<Video>()
    
  • Type constraints can be defined globally

    type Url = string
    
    type Video = {
      url: Url
      length: number
    }
    
    type Image = {
      url: Url
      width: number
      height: number
    }
    
    registerType('Video')
    register('Image')
    
    registerConstraints({
      Url: x => x.startsWith('http://')
    })
    const x = createValidator<Image>()
    const x = createValidator<Video>()
    

ducaale avatar Apr 25 '21 17:04 ducaale

Hey! This makes a lot of sense. will look into this.

vedantroy avatar Apr 27 '21 17:04 vedantroy