Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional Types #197

Merged
merged 21 commits into from
Jul 10, 2022
Merged

Conditional Types #197

merged 21 commits into from
Jul 10, 2022

Conversation

sinclairzx81
Copy link
Owner

@sinclairzx81 sinclairzx81 commented Jul 10, 2022

This PR implements conditional type mapping for TypeBox. It achieves this by replicating TypeScript's structural equivalence rules, and enables for the additional utility types Extract<...> and Exclude<...>. This functionality was considered for 0.24.0 release however required additional updates to inline with the new TypeGuard namespace.

// ----------------------------------------------------
// TypeScript
// ----------------------------------------------------

type A = {
  x: number,
  y: number,
  z: number
}

type B = {
  x: number,
  y: number
}

type X = A extends B ? true : false // true

type Y = B extends A ? true : false // false

// ----------------------------------------------------
// TypeBox
// ----------------------------------------------------

import { Conditional } from '@sinclair/typebox/conditional'
import { Type } from '@sinclair/typebox'

const A = Type.Object({
  x: Type.Number(),
  y: Type.Number(),
  z: Type.Number()
})

const B = Type.Object({
  x: Type.Number(),
  y: Type.Number()
})

const X = Conditional.Extends(A, B,  // { const: true, type: 'boolean' }
  Type.Literal(true), 
  Type.Literal(false)
)
const Y = Conditional.Extends(B, A,  // { const: false, type: 'boolean' }
  Type.Literal(true), 
  Type.Literal(false)
)

Additional

  • Added ReturnType and Parameters for Function utility types.
  • Added ConstructorParameters and InstanceType for Constructor utility types.

@sinclairzx81 sinclairzx81 merged commit edb2487 into master Jul 10, 2022
@sinclairzx81 sinclairzx81 deleted the extends branch July 10, 2022 16:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant