Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract a type from a class in typescript?

Tags:

typescript

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;
like image 693
Joey Yi Zhao Avatar asked Nov 22 '25 10:11

Joey Yi Zhao


2 Answers

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
like image 174
Nikita Madeev Avatar answered Nov 24 '25 22:11

Nikita Madeev


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(...);

enter image description here

like image 31
Ashot Aleqsanyan Avatar answered Nov 25 '25 00:11

Ashot Aleqsanyan



Donate For Us

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