samchon / typia

Super-fast/easy runtime validations and serializations through transformation

Home Page:https://typia.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validation base on dynamic type

machendos opened this issue · comments

I'm retrieving hash maps from Redis in my app. In order to validate value I utilize model map that includes all possible keys and values in Redis. So after retrieving value I want to call validateEquals function and pass type that I recieved dynamically in runtime but in this scenario Typia just never return errors even though they do exist. This flow was working fine with class-validatior but now we decided to go with Typia instead but can't implement this part of functionality. I provide simple code snippet that will show the problem:

enum ModelName {
  A = 'A',
  B = 'B',
}

class ModelA {
  fieldA: number;
}

class ModelB {
  fieldB: number;
}

const ModelSchema: { [key in ModelName]: new (...args: any[]) => any } = {
  [CacheIdentifierPrefix.A]: ModelA,
  [CacheIdentifierPrefix.B]: ModelB,
};

const clientFunction = () => {
  validateFunction(ModelName.A, { wrongValue: 1 });
};

const validateFunction = (modelName: ModelName, value: any) => {
  const model = ModelSchema[modelName];
  console.log(validateEquals<typeof model>(value));
};

clientFunction();

In this case Typia is returning no errors:
{ success: true, errors: [], data: { wrongValue: 1 } }

I can't test your type because do not have the CacheIdentifierPrefix type.

Can you provide me a reproducible repo?

Hi, CacheIdentifierPrefix is just ModelName. Sorry for confusing

Well, in your type, the ModelSchema[modelName] becomes any type.

By the way, if what you want is the class type checking statement represented by instanceof, typia is not performing it. typia does not distinguish class type, but just validates as pritmitive objects.

The class type checking feature would come with "class transformation" feature, but cannot sure when.

No I don't need class type checking(When I validate classes itself). I need check if value that I dynamically provided to the function is satisfy corresponding class definition. So it doesn't necessarily have to be instance of those class. But if class, for instance, have field field1 I want to make sure that value that I passed into also do have this field. In other words, instance has to be implementation of this class. It was easy to do in class-validator, where I was able to pass type(class) that I need to validate for dynamically as function argument