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 基本の型(string・number)

Last updated at Posted at 2025-04-23

はじめに

TypeScriptの学習を始めてみたので環境構築から簡単なコード実行まで試してみた。


前提条件

  • Node.jsがインストール済みであること
    Node.js公式サイトから最新版をインストールする。

TypeScriptコンパイラをインストール

TypeScriptをグローバルにインストールする。

npm install -g typescript
インストール後、バージョン確認:
tsc -v
Version 3.9.5
(2025年時点では最新バージョンは 5.x 系かもしれないので必要に応じてアップデートする)

string型とnumber型を試してみる

index1.ts というファイル名で、以下のコードを作成する。

let message: string = "hello";
console.log(message);

let color: string = 'green';
console.log(color);

let name1: string = `taro`;
console.log(name1);

// この代入はコンパイルエラーになる。
// name1 = 2;

let name2: string = `my name is ${name1}`;
console.log(name2);

let num: number = 30;
console.log(num);

文字列は "ダブルクォート", 'シングルクォート', `バッククォート` いずれも使用可能。
テンプレートリテラル(バッククォート + ${})で文字列中に変数を埋め込める。
: string や : number のように型を明示することで、誤った値の代入を防げる。

実行手順

  1. トランスパイル(TypeScript → JavaScript)
    tsc index1.ts
    同じディレクトリに index1.js が生成される。

  2. 実行(Node.js)
    node index1.js
    hello
    green
    taro
    my name is taro
    30

学んだことのメモ

  • TypeScriptはJavaScriptに型の仕組みを追加した言語である。
  • tsc コマンドはトランスパイラとして、TypeScriptをJavaScriptに変換してくれる。
  • コンパイル時に型エラーをチェックできるので、バグを早期に発見しやすい。
  • チーム開発や中〜大規模開発では、型による安全性が役立つ。
  • Microsoft製の言語であり、Visual Studio Codeとの相性がよさそう。
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?