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、Mapオブジェクトについて

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"

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

Mapオブジェクトについて

  • キーとバリュー(値)のペアを取り扱うオブジェクト
  • 一つのキーに一つの値
  • キーと値それぞれに任意の型を指定できる
  • メソッドによる操作が可能
  • キーの判別は厳密等価
const humanAge = new Map<string,number> ([
    ["taro", 20]
    ["hanako", 18]
    ["tome", 81]
]);

console.log(humanAge.get("taro")); //=>20

Mapオブジェクトと型

Mapオブジェクトそのものの型注釈はMap<Type,Type>

function func(humanAge: Map<string,number>) {}

宣言時に型引数を省略した場合、コンストラクタに引数があれば型推論が発生し、無ければ<any,any>で初期化される。

//型引数の省略
const humanAge = new Map([ //const humanAge: Map<string,number>
    ["taro",20]
];

//型引数とコンストラクタへの引数の省略
const humanAge = new Map(); //const humanAge: Map<any,any>

Mapオブジェクトの操作

次のhumanAgeオブジェクトについて考える

const humanAge = new Map<string,number> ([
    ["taro", 20]
    ["hanako", 18]
    ["tome", 81]
]);

要素追加・上書き set()

  • setメソッドを使用
  • キーが既に存在する場合は値が上書きされる
  • constで宣言されていても追加可能
humanAge.set("sota",30);

キーから値を取得 get()

  • getメソッドを使用
  • .get("キー名")で取得
  • 値がないときはundefinedが返される
console.log(humanAge.get("taro")); //=>20
console.log(humanAge.get("goku")); //=>undefined

要素の削除 delete()

  • deleteメソッドを使用
  • .delete(キー名)で削除
  • キーがあればtrue,なければfalseを返す
humanAge.delete("sota");
console.log("sota"); //=>undefind;

キーの存在確認 has()

  • hasメソッドを使用
  • .has("キー名")で調べる
  • true/falseで返ってくる
    console.log(humanAge.has("taro")); //=>true
    console.log(humanAge.has("goku")); //=>false

要素の個数 size

  • sizeプロパティを参照する

メソッドでないことに注意

console.log(humanAge.size);//=>3

全要素の削除 clear()

  • clearメソッドを使用
humanAge.clear();

キーの列挙 keys()

  • keysメソッドを使用
  • 反復可能オブジェクトを返す

反復可能オブジェクト(iterables object)とは、イテレータを持ち、反復処理が可能なオブジェクトを指す

const humans = [...humanAge.keys()];
console.log(human);//=>["taro","hanako","tome"]

値の列挙 values()

  • valuesメソッドを使用
  • 反復可能オブジェクトを返す
const ages = [...humanAge.values()];
console.log(age);//=>[20,18,81]

キーと値の列挙 entries

  • entriesメソッドを使用
  • 反復可能オブジェクトを返す
  • 後述する配列への変換と動作は同じであるが、キーと値の列挙を明示的に行うことができる
const humanAges = [...humanAge.entries()];
console.log(humanAges);//=>[["taro",20],["hanako",18],["tome",81]]

反復処理

  • for...offorEachを使い、要素を取り出すことができる。
  • 順番は追加した順
for (const [human,age] of humanAge{
    console.log(human,age) //=>"taro",20  "hanako",18  "tome",81
}

他の型との変換

Map ➡ 配列

  • Mapにスプレッド構文を使う
  • 先述したentriesメソッドに比べて、簡潔に記述できる
const humanAgeArray = [...humanAge];
console.log(humanAgeArray)[["taro",20],["hanako",18],["tome",81]]

Map ➡ オブジェクト

`Object.formEntries()にMapオブジェクトを渡す

const humanAgeObj = Object.fromEntries(humanAge);

オブジェクト ➡ Map

Object.entries(オブジェクト)の戻り値をMapコンストラクタ引数にする。

const humanAgeObj = {taro:20}

const humanAge = new Map(object.entries(humanAgeObj));

まとめ

以上になります。

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

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?