typia icon indicating copy to clipboard operation
typia copied to clipboard

Function contracts similar to zod

Open lorefnon opened this issue 1 year ago • 4 comments

Feature Request

Hello, thanks for maintaining and open sourcing typia. I started exploring it recently and it looks great.

Curious if you'd consider adding validated functions similar to zod (Docs).

So given a function like:

const getFullName = (firstName: string, lastName: string): string => `${firstName} ${lastName}`

We'd be able to generate a wrapper that performs validations of input and output but retains the same signature.

const getFullNameGuarded = (firstName: string, lastName: string): string => {
    typia.assertEquals<string>(firstName);
    typia.assertEquals<string>(lastName);
    const out =  `${firstName} ${lastName}`;
    typia.assertEquals<string>(out);
    return out;
}

In case of async function, we'd await on the promise and validate the resolved values.

lorefnon avatar Feb 06 '24 19:02 lorefnon

Which function name do you want about that feature?

May you suggest with function type declaration like one of below?

  • https://github.com/samchon/typia/blob/master/src/module.ts
  • https://github.com/samchon/typia/blob/master/src/protobuf.ts

samchon avatar Feb 07 '24 16:02 samchon

Hi @samchon, thanks for getting back to me. Would something like this be ok?

function guard<TIn extends unknown[], TOut>(impl: (...args: TIn) => TOut): (...args: TIn) => TOut;

function guardAsync<TIn extends unknown[], TOut>(impl: (...args: TIn) => Promise<TOut>): (...args: TIn) => Promise<TOut>;

lorefnon avatar Feb 07 '24 16:02 lorefnon

Then which namespace do you want?

typia.functional.guard(async (value: T1): Promise<O1> => {}) would be okay?

samchon avatar Feb 07 '24 16:02 samchon

Sure, that sounds great.

lorefnon avatar Feb 07 '24 16:02 lorefnon

Upgrade to v5.5 and use like this:

https://typia.io/docs/validators/functional/

samchon avatar Mar 05 '24 18:03 samchon

Thank you 🙂 This is great.

lorefnon avatar Mar 07 '24 22:03 lorefnon