alexeyraspopov / dataclass

Data classes for TypeScript & JavaScript
https://dataclass.js.org
ISC License
181 stars 6 forks source link

Value validation #11

Open m33ch opened 5 years ago

m33ch commented 5 years ago

Hi everyone, I'm trying to figure out how to implement a method to add custom validation.

Some idea? Thanks a lot!

ScreamZ commented 2 years ago

+1 @alexeyraspopov Any idea

alexeyraspopov commented 2 years ago

I'm trying to figure out a way to define some sort of runtime value validation but it should be a complementary API. Right now you can write some sort of custom validation for cases where you need it:

class User extends Data {
  name: string = 'Anon';
  age: number = 0;

  static from(values) {
    let name: string = values.name ?? 'Anon'

    if (isNaN(values.age)) {
      throw new Error('age is missing')
    }

    let age: number = values.age;
    return User.create({ name, age })
  }
}
ScreamZ commented 2 years ago

Maybe we could implement a validate method that does nothing on the parent class, that you can override on the child class if you need validation and throw