alexeyraspopov / dataclass

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

How to use function return value as a field efault value #19

Open ca1f opened 9 months ago

ca1f commented 9 months ago

Hi,

in Python the dataclass type supports calling a factory function to retrieve the default value for a field. For more information you can see here. The parameter is named default_factory for the Field descriptor class which is used to declare extra information for each field.

Is it possible to achieve the same functionality with this package?

alexeyraspopov commented 9 months ago

There is no field() analogy in this library, but you can still call any functions to initialize a property, and the value is going to be used if no custom value provided:

import { Data } from "dataclass";
import { v4 as uuidv4 } from "uuid";

class User extends Data {
  id: string = uuidv4();
}

let a = User.create(); // User { id: "<id generated from uuidv4() call>" }
let b = User.create(); // User { id: "<id generated from uuidv4() call>" }
a.equals(b); // false, IDs are generated for each object separately
let c = User.create({ id: "custom" }); // User { id: "custom" }

I hope this answer the question.

Worth mentioning that the function in property initializer going to be always called during create(), even if there is an explicit property value provided as an argument.