JavaScriptは動的に型を付けるスクリプト言語で、制約が緩い言語です。個人的にはプログラミングを始めるのなら、おすすめの言語です。
しかし、最近では静的型付けが注目されており、JavaScriptにもそれが求められています。
MicroSoftが開発したTypeScriptが今とても注目されています。TypeScriptは型をあらかじめ宣言し、エラーを回避することが可能です。近頃はTypeScriptが求人の条件であったり、求められている会社は増えています。
そこで自身の勉強も兼ねて、TypeScriptの型についてまとめて、初学者の方向けに解説していきます。なお、TypeScriptは文法的にはJavaScriptと全くの同一でありますので、JavaScriptの基礎がわかる方向けの解説となります。
TypeScript解説
では、早速解説をしていきます。
JavaScriptに型がついているのがTypeScriptなので、JavaScript基礎がわかっている前提でいきます。
数値型
const num: number = 113;
const prime: number = 71;
const num1: number = 21.241;
const num2: number = 32e+10;
let num3: number = 10;
let num4: number = 10;
console.log(prime);
console.log(num);
console.log(num1);
console.log(num2);
console.log(num3+num4);
基本的な数値型。
プリミティブ型の一つで、JavaScriptのプリミティブ型と対応している。TypeScriptでは、実数型、整数型の区別はありません。
文字列型
const str: string = "ボルト・ネクジェレ";
const etf: string = "ETFを少しでもいいから買い続けよう";
const money: string = "節約・倹約してお金を増やす";
console.log(str);
console.log(etf);
console.log(money);
基本的な文字列型
プリミティブ型の一つです。
プリミティブその他(null,boolean)
const bool: boolean = true;
const nul: null = null;
const und:undefined = undefined;
console.log(bool);
console.log(nul);
console.log(und);
プリミティブ型
nullやbooleanなどの型も指定できる。JavaScript特有のundefined型もあります。
オブジェクト型
interface Obj1{
name: string;
id: number;
age: number;
}
interface Anime{
title: string;
chapter: number;
term: number;
};
const a: Anime = {title: "Naruto",chapter: 200,term: 10};
オブジェクト型はJavaScriptでもおなじみの型で、自分で任意の型を持つ変数を作ることが可能です。interfaceで宣言し、オブジェクト型名を宣言する。その宣言した型を変数名の型指定で使います。
宣言した型以外のプロパティを宣言、代入しようとするとエラーになります。
配列型
let ary : number[] = [100,2000,3000,40000,500000];
console.log(ary);
ary.forEach(elem => {
console.log(elem);
});
let strAry : string[] = ["ETF","Stock","Bank"];
interface Users{
id: number;
account_id: string;
nickname: string;
follower: number[];
bio: string;
};
const getUsers : Users[] =[
{
id:10,
account_id:"a",
nickname: "b",
follower:[2,4,5],
bio:"ddddddddd",
},
{
id:13,
account_id:"a",
nickname: "b",
follower:[2,4,541,441,2,10],
bio:"ddddddddd",
}
];
配列型はプリミティブ型の直後に[]を付けます。
オブジェクト型の配列も作ることが可能。同様にして[]を付けます。
関数型
function func() : void{
console.log("type script!");
}
const fun = (a:number , b:number):number =>{
return a*b;
}
const isPrime = (n:number):boolean => {
return false;
}
const isUser = (a: string):boolean[] | null =>{
return [true,true,false];
}
関数にも型を宣言することができる。
引数や返り値に型を宣言する。
関数で返り値を返さない場合はvoid型を適用する。
ユニオン(union)型
let val: string | number = 100;
const n: null | boolean = true;
interface UsersA{
id: number;
account_id: string;
nickname: string;
follower: number[];
bio: string;
};
interface UsersB{
id: number;
account_id: string;
nickname: string;
follower: number[];
icon: string;
};
const user: UsersA | UsersB = {
id: 2,
account_id: "faaaa",
nickname: "fffff",
follower:[2,4,541,441,2,10],
icon: "aaaaaaaaaaaaa.png"
}
union型は複数の型のうち、どれかに当てはまる型を代入することが可能です。型を|で繋ぎます。複数の型の値が代入される可能性がある場合などに使用します。もちろん、複数のオブジェクトの型にもunion型を作ることが可能です。
まとめ
今回のまとめに入ります。今回は下記のようなことを解説しました。