TypeScriptにおけるデータ型
この記事ではTypeScriptにおけるデータ型について説明します。
YouTube Video
TypeScriptにおけるデータ型
TypeScriptでは、さまざまなデータ型が提供されています。これにより、変数や関数の引数、戻り値に対して厳密な型を定義できます。以下に主要なデータ型とその使い方を説明します。
プリミティブ型
number(数値型)
1let age: number = 25;
2console.log(age); // Outputs: 25
3console.log(typeof age); // Outputs: number
number
は数値を扱う型で、整数や浮動小数点数(小数)を表すのに使われます。特定の限界を超える値を扱うと、Infinity
やNaN
(Not-a-Number)が発生します。
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
-
TypeScriptでは、数値が浮動小数点数で表現されます。これにより、計算結果にわずかな誤差が生じることがあります。
-
金額など正確な計算が求められる場合、このような丸め誤差を回避する必要があります。例えば、
BigInt
やtoFixed()
を利用したり、decimal.js
などのライブラリを利用して小数点以下の桁数を調整する方法があります。
string(文字列型)
string
型はテキストデータを扱います。
1let greeting: string = "Hello, TypeScript!";
2console.log(greeting); // Outputs: Hello, TypeScript!
3console.log(typeof greeting); // Outputs: string
boolean(論理型)
boolean
型はtrue
またはfalse
の2つの値を持ちます。
1let isOpen: boolean = true;
2console.log(isOpen); // Outputs: true
3console.log(typeof isOpen); // Outputs: boolean
null と undefined
null
は「存在しない値」を表し、undefined
は「未定義の値」を表します。
1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue); // Outputs: null
5console.log(typeof emptyValue); // Outputs: object (JavaScript specification)
6
7console.log(notDefined); // Outputs: undefined
8console.log(typeof notDefined); // Outputs: undefined
配列(Array)
TypeScriptでは、配列の要素の型を指定することができます。number[]
は数値の配列、string[]
は文字列の配列です。
1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers); // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words); // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words); // Outputs: object
タプル(Tuple)
タプルは、要素ごとに異なる型を持つ配列です。
1let person: [string, number] = ["Alice", 30];
2console.log(person); // Outputs: ["Alice", 30]
3console.log(typeof person); // Outputs: object
列挙型(Enum)
enum
は、特定の名前付き定数のセットを定義します。
1enum Color {
2 Red,
3 Green,
4 Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor); // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number
any
any
型は、どんな型の値でも格納できるため、型のチェックを無効化したい場合に使用します。
1let anything: any = "Hello";
2console.log(anything); // Outputs: Hello
3console.log(typeof anything); // Outputs: string
4
5anything = 42;
6console.log(anything); // Outputs: 42
7console.log(typeof anything); // Outputs: number
Union型
Union型を使うと、複数の型のいずれかを持つことができる変数を定義できます。
1let identifier: number | string = "ID_12345";
2console.log(identifier); // Outputs: ID_12345
3console.log(typeof identifier); // Outputs: string
4
5identifier = 12345;
6console.log(identifier); // Outputs: 12345
7console.log(typeof identifier); // Outputs: number
まとめ
number
,string
,boolean
: プリミティブ型です。null
,undefined
: 特殊な値です。Array
: 型注釈付きの配列です。Tuple
: 異なる型の要素を持つ配列です。enum
: 列挙型です。any
: 任意の型です。Union
: 複数の型のどれかを取る変数です。
これらのデータ型を使うことで、TypeScriptでは型の安全性が高まり、開発中にエラーを防ぎやすくなります。
ラッパーオブジェクト
TypeScriptにおけるラッパーオブジェクト(Wrapper Objects)とは、プリミティブ型のデータをオブジェクトとして扱うために自動的に作成されるオブジェクトです。プリミティブ型は軽量で高速な操作が可能ですが、オブジェクト型はメソッドやプロパティを持つため、より豊富な操作ができます。
JavaScript(およびTypeScript)では、プリミティブ型のstring
、number
、boolean
などに対応するラッパーオブジェクトがあります。それぞれString
、Number
、Boolean
というコンストラクタ関数で作成されます。
以下にラッパーオブジェクトの例を示します。
Stringオブジェクト
String
オブジェクトは、文字列に対するプロパティやメソッドを提供します。
1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive); // Outputs: Hello, World!
5console.log(typeof strPrimitive); // Outputs: string
6
7console.log(strObject); // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject); // Outputs: object
特徴:
- プリミティブ型の
string
と異なり、String
オブジェクトはtypeof
でobject
として扱われます。 - ラッパーオブジェクトは、文字列の操作やメソッド呼び出しをする際に便利です。
Numberオブジェクト
Number
オブジェクトは、数値に対するプロパティやメソッドを提供します。
1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive); // Outputs: 42
5console.log(typeof numPrimitive); // Outputs: number
6
7console.log(numObject); // Outputs: [Number: 42]
8console.log(typeof numObject); // Outputs: object
特徴:
Number
オブジェクトは、数値のラッパーとして、数値操作に関するメソッド(例えばtoFixed
など)を持ちます。
Booleanオブジェクト
Boolean
オブジェクトは、真偽値に対するプロパティやメソッドを提供します。
1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive); // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject); // Outputs: [Boolean: true]
8console.log(typeof boolObject); // Outputs: object
特徴:
Boolean
オブジェクトは、プリミティブ型boolean
のラッパーで、object
として扱われます。
ラッパーオブジェクトとプリミティブ型の違い
ラッパーオブジェクトはオブジェクトとして扱われるため、パフォーマンスが若干低下しますが、プロパティやメソッドが追加されるため、より多機能な操作が可能です。また、==
と===
の比較に違いがあります。
1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('== : ', numPrimitive == numObject); // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)
特徴:
==
は値を比較し、===
は型も含めて厳密に比較します。ラッパーオブジェクトとプリミティブ型の比較で===
はfalse
になります。
型の変換
TypeScriptでは、暗黙的および明示的な型変換を適切に管理することが重要です。
暗黙的な型変換
- TypeScriptでは、型の安全性を確保するために、暗黙的な型変換をできるだけ避けるべきです。
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
- この例では、数値の
5
が文字列に暗黙的に変換され、結果は文字列"55"
となります。
明示的な型変換
- TypeScriptでは、型アノテーションや型変換関数を活用して、安全に型変換を行います。
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
- この例では、
Number()
関数を使用して、文字列"123"
を明示的に数値123
に変換しています。
型のチェック
TypeScriptでは typeof
演算子を使って、変数のデータ型を確認できます。
1// Output: The type of 42 is: number
2console.log('The type of 42 is:', typeof 42);
3
4// Output: The type of 42 is: bigint
5console.log('The type of 42n is:', typeof 42n);
6
7// Output: The type of "hello" is: string
8console.log('The type of "hello" is:', typeof "hello");
9
10// Output: The type of true is: boolean
11console.log('The type of true is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol() is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {} is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
- TypeScriptでは
typeof
を使用して型を確認できますが、より厳密な型チェックにはinstanceof
やis
演算子を活用することも推奨されます。
まとめ
- ラッパーオブジェクトは、プリミティブ型に対する追加のメソッドやプロパティを提供するため、オブジェクトとして扱われます。
String
,Number
,Boolean
などがラッパーオブジェクトの代表例です。- プリミティブ型とは異なり、ラッパーオブジェクトは
typeof
でobject
として判別されます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。