Skip to content

Commit

Permalink
fix coercions
Browse files Browse the repository at this point in the history
- improve `InferUncoerced`: the logic to decide what the uncoerced type
is happens in the `coerce` function instead, where it should be
- improve the uncoerced type parameter in the return type of `defaulted`
  • Loading branch information
ziad-saab committed May 10, 2023
1 parent b10c37c commit fb847ca
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
3 changes: 1 addition & 2 deletions src/struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,7 @@ export type Infer<T extends Struct<any, any, any>> = T['TYPE']
* A type utility to extract the type from a `Struct` class before coercion
*/

export type InferUncoerced<T extends Struct<any, any, any>> =
T['TYPE'] | T['UNCOERCED_TYPE']
export type InferUncoerced<T extends Struct<any, any, any>> = T['UNCOERCED_TYPE']

/**
* A type utility to describe that a struct represents a TypeScript type.
Expand Down
18 changes: 9 additions & 9 deletions src/structs/coercions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import { string, unknown } from './types'
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/

export function coerce<T, S, C>(
struct: Struct<T, S>,
condition: Struct<C, any>,
export function coerce<T, S, C, UC>(
struct: Struct<T, S, UC>,
condition: Struct<C, any, any>,
coercer: Coercer<C>
): Struct<T, S, C> {
): Struct<T, S, UC | C | T> {
return new Struct({
...struct,
coercer: (value, ctx) => {
Expand All @@ -35,14 +35,14 @@ export function coerce<T, S, C>(
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/

export function defaulted<T, S>(
struct: Struct<T, S>,
export function defaulted<T, S, C>(
struct: Struct<T, S, C>,
fallback: any,
options: {
strict?: boolean
} = {}
): Struct<T, S, unknown> {
return coerce(struct, unknown(), (x) => {
): Struct<T, S, undefined | Partial<T> | C> {
return coerce(struct, unknown() as Struct<undefined | Partial<T>>, (x) => {
const f = typeof fallback === 'function' ? fallback() : fallback

if (x === undefined) {
Expand Down Expand Up @@ -76,6 +76,6 @@ export function defaulted<T, S>(
* take effect! Using simply `assert()` or `is()` will not use coercion.
*/

export function trimmed<T, S>(struct: Struct<T, S>): Struct<T, S, string> {
export function trimmed<T, S>(struct: Struct<T, S>): Struct<T, S, string| T> {
return coerce(struct, string(), (x) => x.trim())
}

0 comments on commit fb847ca

Please sign in to comment.