はじめに
第2回の今回は「TypeScriptの型の付け方・あつかい方」です。TypeScriptで、さまざまな型をあつかっていきます。
第1章 TypeScriptで型を付ける
前回の記事では、TypeScriptで型を付けるメリットを示しました。今回は、TypeScriptでさまざまな型を付けていきます。
変数や定数への型注釈、型推論
まずは、基本中の基本です。変数や定数に型を加えます。基本的な書き方として、変数名のあとに:
(コロン)を書いて、型を書きます。例を挙げます。
let count: number = 0; let isSucces: boolean = false; let message: string = "hellow"; const not_1: null = null; const not_2: undefined = undefined; let auto = 123;
number
やbolean
、string
といった、JavaScriptのプリミティブ型が指定されています。また、null
やundefined
も型の指定ができます。
最後のauto
の部分は型推論です。123
を代入しているので、number
だと推論されます。VSCode上で、auto
にマウスカーソルを重ねてみてください。ポップアップでlet auto: number
と表示されます。
関数の引数や戻り値への型注釈
変数や定数に型を付けるのと同じように、関数の引数や戻り値にも型を指定できます。
関数の引数には、先に上げた変数や定数の型注釈と同じように「:
(コロン)と型」を書きます。戻り値については、丸括弧のあとに「:
(コロン)と型」を書きます。
function genProfile(name: string, age: number): string { return `${name} (${age})`; } console.log(genProfile('Tom', 10));
console.log
のところのgenProfile
にマウスカーソルを重ねると、function genProfile(name: string, age: number): string
と表示されます。
console.log(genProfile('Tom', 10));
のところを、次のように書き換えてみてください。
console.log(genProfile('Tom', 10) - 1);
そうするとVSCode上で赤線のエラーが表示されます。エラーの内容はThe left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type
(算術演算の左側は、「any」、「number」、「bigint」、または列挙型である必要があります。)です。「-」演算子の左側が「string」(genProfileの戻り値は「string」)のためにエラーが出ています。
型を書くことで、エラーを事前に検出できることが分かります。