Here is a class structure I am currently using:
class Person {
id?: string = uuid();
name: string;
constructor(data: Person) {
_.merge(this, data);
}
}
The 'uuid' function generates an id and '_' refers to lodash.
I am facing an issue where I have a function that requires the id parameter:
function savePersonInDb(p: Person & { id: string }) {...}
However, TypeScript does not allow calling it with a new Person()
instance because id is optional, even though it is always instantiated when calling the constructor.
I am aware that I could modify my class like this:
interface PersonData {
id?: string;
name: string;
}
class Person {
id: string = uuid();
name: string;
constructor(data: PersonData) {
_.merge(this, data);
}
}
However, I am reluctant to rewrite all the attributes twice. Is there a more straightforward way to achieve what I need?
In my actual project, I have numerous attributes, so it would be great if I could avoid duplicating them for every class.
Thank you for your assistance!