1

how should I write my constructor if I am calling it using the following code

const person = new Person({
    name,
    gender
})

where both name and genders are string

Update:

This is what I have got in typescript:

interface Details {
  name: string;
  gender: string;
}

class Person {
  name: string;
  gender: string;
  constructor({ name, gender }: Details) {
    this.name = name;
    this.gender = gender;
  }
}
const person = new Person({
  name: "John",
  gender: "male",
});

console.log(person);
0

1 Answer 1

2

Working Code !!

in JavaScript

class Person {
  constructor({name, gender}) {
    this.name = name;
    this.gender = gender;
  }
}
const name = 'John';
const gender = 'male';
const person = new Person({
  name,
  gender
});
console.log(person);

in TypeScript

interface Details {
  name: string;
  gender: string;
}

class Person implements Details {
  constructor({ name, gender }: Details) {
    this.name = name;
    this.gender = gender;
  }
}
const name = 'John';
const gender = 'male';
const person = new Person({
  name,
  gender
});

console.log(person);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply @solanki... I tried to implement your code in Typescript and this is what I got- ``` interface Details { name: string; gender: string; } class Person { name: string; gender: string; constructor({ name, gender }: Details) { this.name = name; this.gender = gender; } } // const nam = 'John'; // const gender = 'male'; const person = new Person({ name: "John", gender: "male", }); console.log(person); ``` Wondering if you know this is the right way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.