Skip to content

Commit

Permalink
optimize value type infer for Validatable (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
nighca authored Feb 15, 2022
1 parent 0f9df8a commit 4f99901
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Validatable, ValueOf } from './types'

// https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
export type Equal<X, Y> = (
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2)
? true
: false
)

function assertEqual<T, S>(..._args: Equal<T, S> extends true ? [] : [never]) {}

describe('ValueOf', () => {
it('should work well with Validatable', () => {
const a = {} as Validatable<string>
assertEqual<ValueOf<typeof a>, string>()
})
})
10 changes: 9 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,15 @@ export type ValueOfFields<Fields> = (
export type ValueOf<State> = (
State extends FormState<infer Fields>
? ValueOfFields<Fields>
: ValueOfFieldState<State>
: (
State extends FieldState<infer V>
? V
: (
State extends Validatable<unknown, infer V>
? V
: never
)
)
)

/** Validate status. */
Expand Down

0 comments on commit 4f99901

Please sign in to comment.