見出し画像

【ワンピースで覚えるTypeScript】第7回 配列(JavaScript学習者向け)

TypeScriptにおける配列の扱いについてです。

readonlyやオプショナルなど似たものが多いので、取っ付きやすいかと思います。

タプル型は要素数が決まっているので、注意が必要ですね!

const chopper_berry: number[] = [10, 100, 1000];
//number型の値を要素に持つ

//const pirates: number[] = ["ルフィ", "ナミ", "ゾロ"];

const chopper_berry2: Array<number> = [10, 100, 1000];

//型注釈がない場合は型推論で配列の型を得られる
const chopper = ["ヒトヒトの実", 1000, true];

chopper_berry[2] = 10000;
//console.log(chopper_berry);

const chopper_berry3: readonly number[] = [10, 100, 1000];
//chopper_berry3[2] = 10000;

const chopper_berry4 = [10, 100];
chopper_berry4.push(1000);
//console.log(chopper_berry4);
//chopper_berry4.push("チョッパー");
//=> 型推論でnumber[]になっているため
//chopper_berry3.push(10000);
//=> 読み取り専用になっているため

console.log(chopper_berry3.includes(10));

const chopper2: [string, number] = ["ヒトヒトの実", 1000];
chopper2[0];
chopper2[1];
//chopper2[2];
//=> 要素数を超えた位置にアクセスできない

type Chara = [devil_fruit: string, bounty: number];
const chopper3: Chara = ["ヒトヒトの実", 1000];
chopper3[0];
//chopper3[:devil_fruit];
//=> 識別子でアクセスできるわけではない

//読み取り専用タプル型
const chopper4: readonly [string, number] = ["ヒトヒトの実", 1000];
//chopper4[1] = 100;

//オプショナル要素をもつタプル型
type Chara2 = [name: string, bounty: number, devil_fruit?: string];
type Chara3 = [string, number, string?];

const chopper5: Chara2 = ["チョッパー", 1000];

この記事が気に入ったらサポートをしてみませんか?