Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ca1f opened this issue Feb 14, 2024 · 1 comment
Open

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

ca1f opened this issue Feb 14, 2024 · 1 comment

Comments

@ca1f
Copy link

ca1f commented Feb 14, 2024

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
Copy link
Owner

alexeyraspopov commented Feb 19, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants