I have a class:
class Person {
name: string;
age: number;
gender: string;
constructor(params: any){
this.name = params.name;
this.age = params.age;
this.gender = params.gender;
}
}
How can I get a type from the class Person which is equivalent to:
type PersonType = {
name: string;
age: number;
gender: string;
}
so I can use this to for the constructor params type. I don't want to duplicate the code to write the type definition like above code. I am looking for a way to get the type from the class definition.
I don't want to duplicate below code:
name: string;
age: number;
gender: string;
Just specify the class as type
Playground
class Person {
name: string;
age: number;
gender: string;
constructor(params: Person) {
this.name = params.name;
this.age = params.age;
this.gender = params.gender;
this.gender = params.gender2; // error
}
}
const test1 = new Person({ age: 1, gender: '1', name: '1' });
const test2 = new Person({ age: 1, gender: '1' }); // error
Or you can use Object.assign to initialize all fields at once, but then you need to specify a default value for all fields
class Person {
name: string = "default";
age: number = 0;
gender: string = "default";
constructor(params: Person) {
Object.assign(this, params);
}
}
const test3 = new Person({ age: 1, gender: '1', name: '1' });
const test4 = new Person({ age: 1, gender: '1' }); // error
I am not sure, I got you right.
but maybe you want this?
export class Person {
name: string;
age: number;
gender: string;
constructor(params: Person){
this.name = params.name;
this.age = params.age;
this.gender = params.gender;
}
someMethod?: () => void = () => {};
}
Usage Example
const person: Person = new Person(...);

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With