Skip to content

Feature: function argument specific error messages #39

@andykais

Description

@andykais

This may be getting into the territory of custom error reporting (io-ts#error-reporting for example). But it could also just be a special assertion generator. The idea is that I would like to validate a function's parameters. typescript-is provides all the validation I need to make that happen, but the errors it gives back are not as helpful to an end user. This is easier shown than explained:

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never
type Fn = (a: number, b: string) => boolean
type Args = ArgumentTypes<Fn>

const validateFn = createAssertType<ArgumentTypes<Fn>>()
const fn: Fn = (...args) => {
    validateFn(args)
    const [a, b] = args
    return true
}


fn() // TypeGuardError: validation failed at $: expected an array of length 2
// could be: TypeGuardError: validation failed at $: expected 2 arguments

fn(1, 2) // TypeGuardError: validation failed at $.[1]: expected a string
// could be TypeGuardError: validation failed at argument 2: expected a string

fn(1, 'b') // correct usage

I think a wrapAssertFunctionParams<T> would be handy, as a higher order function. Usage would look like:

// generic type argument could be optional
const fnWithValidation = wrapAssertFunctionParams<Fn>(fn)

For the time being I will be writing something myself for my library which does just this. I can post the implementation here if it is interesting

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions