Skip to content

Commit

Permalink
feat(validator): implement literal bigint transform
Browse files Browse the repository at this point in the history
  • Loading branch information
NWYLZW committed Feb 29, 2024
1 parent 3a23124 commit 94049d1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
20 changes: 13 additions & 7 deletions packages/validator/src/types/primitive.bigint.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IsEqual, IsWhat, OnlySubType, t as tn } from '@typp/core'
import type { IsEqual, IsSubType, IsTrue, IsWhat, Not, OnlySubType, t as tn } from '@typp/core'

import { FALSY } from '../base'
import type { SwitchBaseType } from '../base.inner'
Expand Down Expand Up @@ -27,22 +27,28 @@ declare module '@typp/core' {
) : never
boolean:
InputRest extends true ? 1n : InputRest extends false ? 0n : never
// TODO `${Input}n` extends `${O extends bigint}` ? O : never
number: bigint
number: `${InputRest & number}` extends `${infer O extends bigint}` ? O : never
string:
InputRest extends (
| `${bigint}${string}`
| `${infer O extends bigint}${string}`
| `0${'b' | 'B'}${string}`
| `0${'o' | 'O'}${number}`
| `0${'x' | 'X'}${string}`
) ? bigint
: true extends IsEqual<InputRest, string>
) ? (
Not<IsWhat<O, never>> extends true
? O
: bigint
) : true extends IsEqual<InputRest, string>
? unknown
: never
symbol: never
null: 0n
undefined: 0n
}>
}> extends infer Result ? (
IsWhat<T, bigint> extends true ? Result : (
IsTrue<IsSubType<Result, T>> extends true ? Result : never
)
) : never
]
}
}
Expand Down
24 changes: 24 additions & 0 deletions packages/validator/tests/types/literal.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,28 @@ describe('literal primitive', () => {
}).toThrow()
})
})
describe('transform', () => {
test('bigint', () => {
const zeroBigIntSkm = t.const(0n)
const r0 = zeroBigIntSkm.parse(0n)
expect(r0).toBe(0n)
expectTypeOf(r0).toEqualTypeOf<0n>()

const r1 = zeroBigIntSkm.parse.narrow(0)
expect(r1).toBe(0n)
expectTypeOf(r1).toEqualTypeOf<0n>()

const r2 = zeroBigIntSkm.parse.narrow('0')
expect(r2).toBe(0n)
expectTypeOf(r2).toEqualTypeOf<0n>()
expect(() => {
const r0 = zeroBigIntSkm.parse(1)
expectTypeOf(r0).toEqualTypeOf<never>()
}).toThrow()
expect(() => {
const r0 = zeroBigIntSkm.parse('1')
expectTypeOf(r0).toEqualTypeOf<never>()
}).toThrow()
})
})
})

0 comments on commit 94049d1

Please sign in to comment.