Help us understand the problem. What is going on with this article?

TypeScriptでobjectの値の参照渡しでコケた時の回避方法

何をしようとしたか

特定の項目が同じ値のままUserを使いまわそうとした。
今回の例だと User.age

entities/User.ts
export class User {
  name: string;
  age: number;
}
typescript/main.ts
import { User } from "./entities/User";

export const main = () => {
  let users: User[] = [];

  let user: User = { name: "alpha", age: 20 };
  users.push(user);

  // nameのみ変更
  user.name = "beta";
  users.push(user);

  console.log({ users });
};

main();

求めていた結果

{ users: [ { name: 'alpha', age: 20 }, { name: 'beta', age: 20 } ] }

実際に出てきた結果

{ users: [ { name: 'beta', age: 20 }, { name: 'beta', age: 20 } ] }

betaくんが2人になってる…

回避手段

調べたらjavascriptはobjectの場合、値の参照渡しを行うらしい

なら毎回新しいobjectを生成すればいいのかと思った

丁度nestjsを使用していたので、class-transformer/plainToClassを使用することにした

npm i class-transformer
main.ts
import { plainToClass } from "class-transformer";
import { User } from "./entities/User";

export const main = () => {
  let users: User[] = [];
  let user: User = { name: "alpha", age: 20 };
  users.push(plainToClass(User, user));
  user.name = "beta";
  users.push(plainToClass(User, user));

  console.log({ users });
};

main();

実行結果

{  users: [ User { name: 'alpha', age: 20 }, User { name: 'beta', age: 20 } ]}

求めている形で返ってきた

感想

objectの取り扱いには気をつけよう
そもそも使いまわしたい部分に対して処理をちゃんと書けばこうならなかったはず
とりあえず動かしたい精神で書いてたら死んだ

参考

[Qiita]JavaScriptに参照渡し/値渡しなど存在しない

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away