samchon / typia

Super-fast/easy runtime validators and serializers via transformation
https://typia.io/
MIT License
4.45k stars 153 forks source link

Extraction of Sub-Validation Functions from Composite Typia Validation Functions #926

Open wesselvdv opened 7 months ago

wesselvdv commented 7 months ago

Feature Request

samchon commented 7 months ago

No idea how to.

typia is generating nested validator functions per each object types. Your idea seems good, but I don't have idea how to declare the type definition. As you know, current typia.createIs() function returns just boolean returing function type. To accomplish this goal, need to make a special TMP type (IsFunction<T>) like below.

https://typia.io/playground/?script=JYWwDg9gTgLgBDAnmYBDANHA3g1BzAZzgF84AzKCEOAIiRVRoG4AoF4AOxgFMozUAxtzgBJALLcQAI17YWcBXGAATAFxwCMKJzxwAZLkIA6AGLQQqGAB4aAV1sqaAPlaK4k1MAA26zdo66BjD4BKbmljYe3s6uivjc6hy20rLybopBIUYAKsjcNg5cAMwATM5waen6hqFinKDJViUADE4VVQqZxgCiAB4CXrYEwABu3GKovQ0gVgCMza2xCmCoUNxc6uKSMlBwAD5wSV5eS3ACABbeymscmxIpUADaALqn5xBSUsDcBJsAEh8pIgXqxiGxODw+IJhCIAZ9EHI3BxUCAEhotDpQWwAPTYgC0BLxLFxcAAagBBAAyIgAIuTsiIAPIAOWJ+MJLHoaCMAjWlm4IgIVi2DycAAoAJSsIA

Of course, in the IsFunction type, it must have not only input is T returning function type, but also nested function types per each object types. In your example case, nested function isEmployee() and isProduct() must be automatically declared by the EmployeeProductAssignment<T> type. In my knowledge, it seems not possible in the current TypeScript spec, but not exact.

If this feature be possible, it would be really revolutionary feature for convenience. Will you research about it?

// CURRENT
export function createIs<T>(): (input: unknown): input is T;

// MUST BE
export function createIs<T>(): (input: unknown): IsFunction<T>;

// FOR EXAMPLE
type IsFunction<EmployeeProductAssignment> := ((input: unknown) => input is EmployeeProductAssignment) & {
  isEmployee: (input: unknown) => input is Employee;
  isProduct: (input: unknown) => input is Product;
};
wesselvdv commented 7 months ago

Yes, I see your point. I reckon this is not possible with Typescript atm. How about we make it bit more manual, so you can basically "extract" a validator:

import typia from "typia";

interface Employee {
    // Employee fields
}

interface Product {
    // Product fields
}

interface EmployeeProductAssignment {
    employee: Employee;
    product: Product;
}

const isAssignment = typia.createIs<EmployeeProductAssignment>();

// Proposed method to extract sub-validation functions
const { isEmployee, isProduct } = isAssignment.getValidators<{ isEmployee: Employee, isProduct: Product }>();

const employee = { /* employee data */ };
const product = { /* product data */ };

// Now we can use these individual functions instead of regenerating them
const isEmployeeValid = isEmployee(employee);
const isProductValid = isProduct(product);

This way you circumvent the need for "auto" typing all nested validators.