TypeScriptの型の書き方

TypeScriptとは
TypeScriptとは、JavaScriptを拡張して作られたプログラミング言語です。
2014年頃にMicrosoftによって開発・発表されています。
TypeScriptは変数、引数に型の指定ができるので、コンパイル時にエラー確認ができるので、JavaScriptと異なりプログラム実行エラーよりバグも事前に防ぐことができます。TypeScriptで書かれたコードをコンパイルするとJavaScriptのコードに変換されます。
TypeScriptでJavaScriptのライブラリは使用することもできます。
TypeScriptの型の種類

プログラミングで共通で使う、よく使う型です。
- String型
- Number型
- Bool型
- Array型
- Object型
- Any型
型を書く場合は先頭の文字は大文字ではなく小文字で記述します。
String → string Number → number Boolean → boolean
スポンサードサーチ
型を使うとタイミング

宣言をする場合、値を使用する場合は型を指定します。
- 変数
- 関数
- 引数
- 可変長引数
プリミティブ型
変数宣言
let num: number; let str: string; let bool: boolean;
代入結果
num = 123; num = 123.456; num = '123'; // Error str = '123'; str = 123; // Error bool = true; bool = false; bool = 'false'; // Error
スポンサードサーチ
配列型・Array
空の配列
let array: number[] = [];

配列宣言には型とからの配列を記述します。
配列にNumber型を代入
let array1: Array<number> = [1, 2, 3]; console.log(array1); let array2: number[] = [4, 5, 6]; console.log(array2);

Array<number>の記述は非推奨なので、nuber[]で記述が今の記述です。
配列にBooleanを代入
let boolArray: boolean[]; boolArray = [true, false]; console.log(boolArray[0]); // true console.log(boolArray.length); // 2 boolArray[1] = true; boolArray = [false, false]; boolArray[0] = 'false'; // Error! boolArray = 'false'; // Error! boolArray = [true, 'false']; // Error!
タプル型・型混合の配列

複数の異なる型の集合体タプル型と言います。
下記のように型混合で配列を作ることもできます。
let array: [string, number] = ["hoge", 1]; console.log(array) // ["hoge", 1]

Any型はどんな型が来ても大丈夫な型です。
let array: any[]; array5 = ['kami', 'hoge', 1]; console.log(array) // [ 'kami', 'hoge', 1]
スポンサードサーチ
二次元配列
let nijigenArray: string[][] = [ ['hoge1','hoge2'], ['hoge3', 'hoge4'] ] console.log(nijigenArray) // [ [ 'hoge1', 'hoge2' ], [ 'hoge3', 'hoge4' ] ]
タプル型と二次元配列の応用
let nijigenArray2: [string, number][] = [ ['hoge1', 1], ['hoge2', 2] ] console.log(nijigenArray2) // [ [ 'hoge1', 1 ], [ 'hoge2', 2 ] ]
配列内に配列を入れることもできます。
let array: any[]; array5 = ['kami', 'hoge', 1, nijigenArray2]; console.log(array) // [ 'kami', 'hoge', 1, [ [ 'hoge1', 1 ], [ 'hoge2', 2 ] ] ]
オブジェクト型・Object
オブジェクトでの定義のログの確認です。
let user: { a: string, b:number } = { a: "kami", b: 1 }; console.log(typeof user); // object console.log(user.a) // kami console.log(user.b) // 1
オブジェクト型を取得
const user: User = { name: 'kami', age: 35, sex: 'man', other: '', } interface User { name: string, age: number, sex: string, other: string | null, } console.log(user); // { name: 'kami', age: 35, sex: 'man', other: '' } console.log(JSON.stringify(user)) // {"name":"kami","age":35,"sex":"man","other":""}
オブジェクト型は型定義の部分を取得するには、interfaceを使います。
オブジェクト型に代入する
interface User { name: string, age: number, sex: string, other: string | null, } let user: User = { name: 'kamiblog', age: 25, sex: 'woman', other: 'メモです', } console.log(user); // { name: 'kamiblog', age: 25, sex: 'woman', other: 'メモです' }
オブジェクトの値をの前にinterfaceを宣言して、値を代入するとその値を変数に入れることができます。
enum・挙型
enum User { NAME, NUMBER } let u:User = User.NAME; console.log(u) // 0 console.log(User[u]) // NAME
挙型もオブジェクト型と同じように値のindexと値を取得することができます。
null型, undefined型
const hoge = null const foo = undefined console.log(hoge == null) // true console.log(hoge == undefined) // true console.log(foo == null) // true console.log(foo == undefined) // true console.log(hoge === null) // true console.log(hoge === undefined) // false console.log(foo === null) // false console.log(foo === undefined) // true
==での値比較はどちらもtrue,
===での比較では型までチェックするため、falseになります。
const hoge: Hoge = { firestname: null, endname: undefined, } interface Hoge { firestname: String | null, endname: String | undefined, } console.log(hoge) // { firestname: null, endname: undefined } const hoge: Hoge = { firestname: 'null', endname: 'undefined', } interface Hoge { firestname: String | null, endname: String | undefined, } console.log(hoge) // { firestname: 'null', endname: 'undefined' }
HTMLElement型
classを使った例でHTMLElementのサンプル実装をしています。
// index.js import Hoge from "./hoge" // htmlElement型のroot変数を用意 const root: HTMLElement | null = document.getElementById('root') // インスタンス化 const hoge = new Hoge('kamiblog typescript') hoge.showText(root)
index.jsでhogeクラスをimportしてインスタンス化しています。
インスタンス後にhogeクラスのshowText関数を使用しています。
// hoge.js export default class Hoge { message: string; constructor(message: string) { this.message = message } public showText(elem: HTMLElement | null) { if(elem) { elem.innerText = this.message } } }
hogeクラスのshotText関数でHTMLElement型の取得をおこなっています。
関数
let a : String = 'kamiblog'; let b: boolean = true; function hoge = (a: String, b: boolean): Boolean { return b; } console.log(hoge(a, b)) // true
関数の引数の指定とreturnする方も指定してください。
アロー関数
let a : String = 'kamiblog'; let b: boolean = true; const hoge = (a: String, b: boolean): String => { return a; } console.log(hoge(a, b)) // kamiblog
アロー関数もfunction関数と同様で、引数と戻り値の指定をしてください。
実装やエラーが解決できない場合
プログラミングの実装やエラーでどうしてもわからない場合はメンターに相談するのが一番です。
考えている、見えている範囲が狭くなり、解決から遠くに行って何時間も、何日も経っていることなんてよくある話です。
そういう時は聞ける先輩や、メンターに相談することが大事です。
僕にも相談可能なので気軽に相談してください。

Twitterからの連絡だと確実ですよ。
オンラインスクールやプログラミングスクールといったプログラミングを学べる方法もあるので、そちらもぜひ活用してもいいと思います。
Web開発で分からない時
オンライン完結型スクール DMM WEBCAMP PROアプリ開発で分からない時
プログラミング×稼げる副業スキルはテックキャンププログラミングについて分からない時
【コエテコ様限定】※ご案内を受けた以外のメディアが使用しても成果は承認されません。
僕への個人でもメンターでも、スクールでもお好きな方を活用ください。