LoginSignup
1
0

More than 1 year has passed since last update.

【JavaScript/TypeScript】?.・?・|

Posted at

最近使い始めたTypeScriptで気になったものがあったので調べました。TypeScript固有かと思ったらJavaScriptでも使えるものもありました。

?. オプショナルチェーン

※TypeScript/JavaScriptで使用可能

プロパティの最後に付与することで、プロパティ参照を安全にできる。
目的のオブジェクト・プロパティにアクセスする前に暗黙的にnull または undefinedかどうかを確認する。(値がnullundefinedならundefinedが返る)

特にネストしたオブジェクト・プロパティのnullundefinedチェックをif文よりも簡潔に書くことができる。

interface Contact {
  emailAddress: string,
  phoneNumber: string,
}

interface Person {
  id: number,
  name: string,
  contact: Contact
}

const person: Person = undefined

const emailAddress1 = 
  person == null || person == undefined ? undefined
: person.contact == null || person.contact == undefined ? undefined
: person.contact.emailAddress;

//emailAddress1よりも簡潔に書くことが出来る
const emailAddress2 =  person?.contact?.emailAddress 

? オプショナルプロパティ

※TypeScriptのみ使用可能

プロパティの最後に付与することで任意プロパティとすることができる。
例えばアンケートで入力不要な項目など、必須ではないプロパティに付与することでコードの記述量を減らすことができる。

interface Enquete {
  name?: string,
  sex: string,
  age: number,
}

function getEnquete(enquete: Enquete) {
  //...
}

//nameプロパティの指定が不要になる
const enquete1 = getEnquete({ sex: "female", age: 20 }); 
const enquete2 = getEnquete({ name: "Bob", sex: "male", age: 25 });

| ユニオン型

※TypeScriptのみ

ユニオン型は1つの値に対してなりうる型を複数指定することができる。複数の型を許可しつつも、型に制限をかけたいときなどに使用する。

type Car = {
  //...
};

type Train = {
  //...
};

type Airplane = {
  //...
};

type Vehicle = Car | Train | Airplane;

let vehicleList: Vehicle[] = [
  //Car/Train/Airplaneしか配列に追加できない
];

参考

1
0
1

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
1
0