TypeScriptの型の書き方

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

プログラミングで共通で使う、よく使う型です。
- String型
- Number型
- Bool型
- Array型
- Object型
スポンサードサーチ
型を使うとタイミング

宣言をする場合、値を使用する場合は型を指定します。
- 変数
- 関数
- 引数
- 可変長引数
プリミティブ型
変数宣言
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);
配列に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!
オブジェクト型・Object
オブジェクト型を取得
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を宣言して、値を代入するとその値を変数に入れることができます。
スポンサードサーチ
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アプリ開発で分からない時
プログラミング×稼げる副業スキルはテックキャンププログラミングについて分からない時
【コエテコ様限定】※ご案内を受けた以外のメディアが使用しても成果は承認されません。
僕への個人でもメンターでも、スクールでもお好きな方を活用ください。