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入門 #3 条件分岐・関数

0
Posted at

はじめに

TypeScriptの学習を始めたので、復習も兼ねて備忘録として残します。

今回は条件分岐と関数について。

条件分岐

if文

条件によって処理を変えたい場合は if を使用する。

const age: number = 20;

if (age >= 18) {
  console.log("成人です");
}

条件に当てはまらなかった場合の処理を追加する場合は else。

const age: number = 17;

if (age >= 18) {
  console.log("成人です");
} else {
  console.log("未成年です");
}

複数の条件を指定する場合は else if を使用する。

const score: number = 80;

if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}

比較演算子

よく使用するもの。

演算子 内容
=== 等しい
!== 等しくない
> より大きい
>= 以上
< より小さい
<= 以下
const value = 10;

if (value === 10) {
  console.log("10です");
}

== ではなく、基本的には === を使用する。

=== は値だけでなく型も含めて比較する。

複数の条件を指定する

AND

両方の条件を満たす場合は &&。

const age = 20;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("入場できます");
}

OR

どちらかの条件を満たす場合は ||。

const isAdmin = false;
const isOwner = true;

if (isAdmin || isOwner) {
  console.log("編集できます");
}

NOT

! をつけると true / false を反転できる。

const isLoggedIn = false;

if (!isLoggedIn) {
  console.log("ログインしてください");
}

関数

同じような処理をまとめたい場合に関数を使用する。

function greet(name: string): void {
  console.log(`こんにちは、${name}さん`);
}

greet("田中");

name: string で引数の型を指定。

今回は値を返していないので、戻り値は void。

値を返す

値を返したい場合は return を使用する。

function add(a: number, b: number): number {
  return a + b;
}

const result = add(10, 20);

console.log(result);
// 30

: number の部分が戻り値の型。

PHPだと下記のような感じなので、考え方はそこまで変わらなそう。

function add(int $a, int $b): int
{
    return $a + $b;
}

アロー関数

TypeScriptではアロー関数もよく使用する。

const add = (a: number, b: number): number => {
  return a + b;
};

1行で返せる場合は短く書くこともできる。

const add = (a: number, b: number): number => a + b;

ReactやNext.jsのコードを見ているとよく出てくるので、この書き方には慣れておきたい。

オブジェクトを関数に渡す

オブジェクトを引数として渡す場合。

type User = {
  name: string;
  age: number;
};

const showUser = (user: User): void => {
  console.log(`${user.name}さんは${user.age}歳です`);
};

showUser({
  name: "田中",
  age: 25,
});

先に type で型を定義しておくと分かりやすい。

配列と関数

配列の中身を順番に処理する場合は forEach が使用できる。

const tasks: string[] = [
  "メール返信",
  "買い物",
  "勉強",
];

tasks.forEach((task) => {
  console.log(task);
});

条件分岐と組み合わせることもできる。

const scores: number[] = [50, 80, 90, 60];

scores.forEach((score) => {
  if (score >= 70) {
    console.log(`${score}点:合格`);
  }
});

まとめ

今回は条件分岐と関数について確認した。

特に関数は、

  • 引数の型
  • 戻り値の型

を指定するところがTypeScriptでよく使いそう。

アロー関数もReact / Next.jsでよく見るので、書きながら慣れていきたい。

次は配列操作でよく使用する map、filter、find あたりを確認する。

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?