0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【超基礎】TypeScript、Setオブジェクトについて

Posted at

前提

この記事は、初学者の私が、サバイバルTypeScriptで学んだこと+調べたことをまとめたものになります。

従って、経験則に基づいた発言ではないため、一部慣習とは違っていたり、認知にずれがあったりする可能性がありますので、ぜひコメントで指摘していただけると幸いです。

環境

記事内のコードは以下の環境で動作確認済みです。

  • Node.js: v22.10.0
  • TypeScript: Version 5.6.3

tscでそのままコンパイルしたところ、

error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing he 'lib' compiler option to 'es2015' or later.

のエラーが出たため

tsc increment.ts --lib "es2015,dom"

でコンパイルしています。

setオブジェクトとは?

  • 組み込みAPIの一つ
  • 値の重複を許さない
  • 重複した値は削除される
実装例
const humans = new Set<string>(["taro","hanako","taro"]);
console.log(humans)//=>Set(2) {'taro','hanako'}

宣言

  • new Set<Type>([])で宣言する
  • コンストラクタには初期値を配列で渡す
  • 型引数の無い、空のSetオブジェクトはunknownになる
    ➡後から値を入れたい場合は宣言時に必ず型注釈をつける
Setの宣言
//初期値を配列で渡す
//型推論が発生
const humans1 = new Set(["taro","hanako"]);

//型注釈が必須
const humans2 = new Set<string>([])

Setと型

  • 先述の通り初期値なしの宣言はunknown
  • ユニオン型により複数の型の格納が可能
  • 型注釈はSet<Type>
const humansNum = new Set<string|number>(["taro","hanako",50])
console.log(humansNum);//=>Set(3) {"taro","hanako",50}

操作

メソッドによる操作が可能
以下のSetオブジェクトについて考える

const humans = new Set<string>(["taro","hanako",]);

値の追加 add()

  • addメソッドを使用(Mapオブジェクトではset)
  • 同じ値は何度追加しても増えない
humans.add("tome")

console.log(humans)//=>Set(3){"taro","hanako","tome"}

値の削除 delete()

  • deleteメソッドを使用(Mapオブジェクトと同じ)
  • 値があればtrue、なければfalseを返す
humans.delete("taro");

console.log(humans)//=>Set(1){"hanako"}

値の個数を取得 size

  • sizeプロパティを参照(Mapオブジェクトと同じ)
console.log(humans.size)//=>2

Setを空にする clear

  • clearメソッドを使用(Mapオブジェクトと同じ)
humans.clear();
console.log(humans);//=>Set(0){}

Setの反復

  • `for-of構文でループ可能
  • 追加した順に取り出す

確認時にエラーが出たためtsc increment.ts --lib "es2015,dom" --downlevelIterationで実行しました。

const humans = new Set<string>(["taro","hanako",]);

for (const human of humans){
    console.log(human);
}

他のオブジェクトとの変換

Set ➡ 配列

- スプレッド構文を使用
- Array.from()でも可能

const humansArray1 = [...humans];
const humansArray2 = Array.from(humans);

console.log(humansArray1);//=>["taro","hanako"]
console.log(humansArray2);//=>["taro","hanako"]

Set ➡ JSON

  • 直接JSONにはできない
  • 一度配列に直す
console.log(JSON.stringify(humans));//=> {}

humansArray = [...humans];

console.log(JSON.stringify(humansArray));//["taro","hanako"]

まとめ

以上になります。

慣例から外れた部分があれば指摘していただけると幸いです!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?