0

I am unable to figure out the reason why summary() when destructured in printVehicle returns undefined. Whereas it works fine and returns Civic without destructuring by using oldVehicle.summary() .

interface Vehicle {
  name: string;
  year: number;
  broken: boolean;
  summary(): string;
}

const oldCivic = {
  name: 'Civic',
  year: 2000,
  broken: true,
  summary(): string {
    return this.name;
  }
};

console.log(oldCivic.summary());

const printVehicle = ({ name, year, broken, summary }: Vehicle): void => {
  console.log(`
    Name: ${name}
    Year: ${year}
    broken: ${broken}
    summary: ${summary()}
    `);
};
printVehicle(oldCivic);

  • Why do you think it's `undefined`? https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGoQBbAQGxQbwChlkQ4BbCALmQGcwpQBzAbmOQE8I4oaQBXcgCNobEkKgB7ANYQQNIZMl44IMXUHkeHABQBKGvUYhWhAL6FCCSSHrJlAEwDCwAG7ZkAXmRESZSjQA5C7uCIEANOxcPDQATAAMiZHiUrLyyAz8EMka5FpQugZ0DMw+7CRQEGD8UCAZWLQAdP4Q6hZmbFY2tMoQjTiSTDqOIdiNtJra+nqd1rZgyAAOxmDoWLgo3jr4pBTZnNxQ4cgSMnLHE3nayGY0a9h4Ra6SwA5eAHxlJHM9eP2DOgABuVkAA5PY0AAk+BaFhIJAAmocofholA4fDTmkUVi5BiSJd8hwUYSpnp8chATNzGxlqBVpgHhBhjhnG5sDMgA – zerkms Feb 15 '21 at 08:33
  • It works actually no ? https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGoQBbAQGxQbwChlkQ4BbCALmQGcwpQBzAbmOQE8I4oaQBXcgCNobEkKgB7ANYQQNIZMl44IMXUHkeHABQBKGvUYhWhAL6FCCSSHrJlAEwDCwAG7ZkAXmRESZSjQA5C7uCIEANOxcPDQATAAMiZHiUrLyyAz8EMka5FpQugZ0DMw+7CRQEGD8UCAZWLQAdP4Q6hZmbFY2tMoQjTiSTDqOIdiNtJra+nqd1rZgyAAOxmDoWLgo3jr4pBTZnNxQ4cgSMnLHE3nayGY0a9h4Ra6SwA5eAHxlJHM9eP2DOgABuVkAA5PY0AAk+BaFhIJAAmocofholA4fDTmkUVi5BiSJd8hwUYSpnp8chATNzGxlqBVpgHhBhjhnG5sDMgA – Maxime Chevallier Feb 15 '21 at 08:37
  • 1
    @MaquessimeChevallier it throws an error in the console. – VLAZ Feb 15 '21 at 08:42
  • The issue is that when you destructure a function, then upon executing you won't get the correct `this`. You either need to make `summary` an arrow function, bind `this` in the contructor, or *not* destructure it. Your last option is to destructure but have a reference to the original object and use `summary.call(obj)` but at that point you're just doing more effort to re-write `obj.summary()`, so I don't think it's a good option. – VLAZ Feb 15 '21 at 08:45

0 Answers0