TypeScript の基本

typeScript 公開日: 2022-04-23 更新: 2022-04-26

参考リンク

ts-node をインストール

npm install -D ts-node

主な TypeScript の型

  • boolean
  • number
  • string
  • any
  • void
  • Array
  • Object
  • undefined
  • nullable

boolean型, number型, string型について

boolean型とnumber型とstring型を使う方法open in new window

let boolVal = false;
// typeof(boolVal) = boolean

// Typescript では整数 int, 少数 float, マイナス値 いずれも "number"型
let num = 123
// typeof(num) = number

let num2 = 123.456
// typeof(num2) = number

let num3 = -123
// typeof(num3) = number

// シングルクォート, ダブルクォート, バッククォート いずれも "string"型
let str = 'howdy';
// typeof(str) = string

let str2 = "hey";
// typeof(str2) = string

let str3 = `goodDay`;
// typeof(str3) = string

オブジェクト型

オブジェクトの型注釈 (type annotation)open in new window

// インライン型注釈 (プロパティの区切り文字にカンマ,も使えるが、セミコロン; を用いる方が良い)
let person: { name: string; age: number; hobby?: string };

person = { name: 'Mike', age: 22, hobby: 'fishing' }
// person: {name: 'Mike', age: 22, hobby: 'fishing'}

// 改行して型注釈 (改行した場合、プロパティの区切り文字は省略可)
let person: {
  name: string
  age: number
  hobby?: string
};

person = { name: 'Mike', age: 22, hobby: 'fishing' }
// person: {name: 'Mike', age: 22, hobby: 'fishing'}

型エイリアス type を使った型注釈

type Person = {
  name: string,
  age: number,
  hobby?: string
};

const person: Person = { name: 'Mike', age: 22, hobby: 'fishing'};
// person: {name: 'Mike', age: 22, hobby: 'fishing'}

型エイリアスはさまざまな型に名前をつけられる

// 型エイリアス 使用例
// プリミティブ型
type Str = string;
// リテラル型
type OK = 200;
// 配列型
type Numbers = number[];
// オブジェクト型
type UserObject = { id: number; name: string };
// ユニオン型
type NumberOrNull = number | null;
// 関数型
type CallbackFunction = (value: string) => boolean;

TIP

型エイリアスは同じ型を再利用したいときに使うと便利で、型の定義が一箇所になるため、保守性が向上する。また、型に名前を与えることで可読性の観点でも良い

関数をプロパティに持つオブジェクト(メソッド)の型注釈

let calculator: {
  sum: (x: number, y: number) => number;
  mean: (x: number, y: number) => number;
};

calculator = {
  sum: (x, y) => x + y,
  mean: (x, y) => (x + y) / 2
};

console.log("🚀 ~ file: calculator.sum", calculator.sum(5, 10)); // 15
console.log("🚀 ~ file: calculator.mean", calculator.mean(5, 10)); // 7.5


const culc = {
  sum: (x: number, y: number) :number => x + y,
  mean: (x: number, y: number) :number => (x + y) / 2
}

console.log("🚀 ~ file: culc.mean(5, 10)", culc.sum(5, 10)); // 15
console.log("🚀 ~ file: culc.mean(5, 10)", culc.mean(5, 10)); // 7.5

キーバリューのオブジェクト型を定義 ユーティリティ型 Record<Keys, Type>

Record<Keys, Type>open in new window

let scores: Record<string, number>;

scores = {
  '国語': 78,
  '数学': 56,
  '英語': 98,
};
// console.log(scores); {国語: 78, 数学: 56, 英語: 98}

// キーが "国語", "数学", "英語" のいずれかのみ、値が 数値のオブジェクト型
let limitedScore: Record<"国語" | "数学" | "英語", number>

limitedScore = {
  '国語': 78,
  '数学': 56,
  '英語': 98,
  // '科学': 88 // 👈 エラー
};
// console.log(limitedScore);  {国語: 78, 数学: 56, 英語: 98}

object型 (なるべく使用しない)

object、Object、{}の違いopen in new window

object型には何のプロパティがあるかの情報がない為、プロパティの参照不可

let personB: object;
personB = {name: 'David', age: 29}

// personB.nameを参照しようとするとコンパイルエラー
personB.name // Property 'width' does not exist on type 'object'.

配列の型注釈

配列の型注釈open in new window

// 要素の型の後ろに[]をつける書き方
let arr: number[];
arr = [1, 2, 3]

// Array<要素の型>を用いる書き方
let array: Array<number>;
array = [1, 2, 3]

// 要素が文字列 or 数値の配列
let newArr: (string | number)[];
newArr = [1, 'a', 20, 'abc']

タプル Tuple型で、決まった内容の配列を生成

タプル (tuple)open in new window

// 要素が3つで、 1つめが 文字列, 2つめが 数値, 3つめが 真偽値 の配列
let fixedArr: [string, number, boolean];
fixedArr = ['abc', 123, true] // OK
fixedArr = [3, 2, 'yes'] // 👈 1,3つめの要素が型エラー🚫

ただし、 arr.push() で4つめの要素を追加してもエラーにはならない(参照しようとするとエラー)

列挙型 enum 特定のまとまったグループのみを受け入れる型

列挙型 (enum)open in new window

enum ShoeFor {
  Men = 'Men',
  Women = 'Women'
};

let shoe: {
  size: number;
  shoeFor: ShoeFor
}

shoe = {
  size: 25.5,
  // shoeFor: 'Women' // 👈 エラー
  shoeFor: ShoeFor.Women // OK❗ ShoeFor.Men' or ShoeFor.Women のみ
}

列挙型の代替として、できればユニオン型を使った方がベター?

ユニオン型 (union type) 複数のうちいずれかの型

// 文字列 or 数値 の変数
let unionType: string | number;
unionType = 'union'
unionType.toUpperCase() // 'UNION'

unionType = 100
// unionType.toUpperCase() // 👈 エラー🚱 `Property 'toUpperCase' does not exist on type 'number'`

// 文字列 or 数値 の値を要素にもつ配列
let arrUnionTypes: (string | number)[];
arrUnionTypes = ['union', 100]

型エイリアス (type alias) と ユニオン型 (union type) を組み合わせて利用

type Shoe = {
  size: number;
  shoeFor: 'Men' | 'Women'
};

const newShow: Shoe = {
  size: 25,
  shoeFor: 'Men'
  // shoeFor: 'boy' // 👈 エラー🚱 `Type '"boy"' is not assignable to type '"Men" | "Women"`
}

関数に型を定義

// const calcSum = (a ,b) => a + b;

const calcSum = (a: number ,b: number) : number => a + b;
const sum = calcSum(5, 10)
// console.log("sum", sum); // 15

// or

type CalcSum = (a: number ,b: number) => number;
const getSumNumber: CalcSum = (a: number ,b: number) => a + b;
const sumNum = getSumNumber(5, 10)
// console.log("sumNum", sumNum); // 15

何も値を返さない関数の型 void型

function greeting(msg: string, name: string) :void {
  console.log(`${msg} ${name}`);
};

greeting('hey', 'Michel')

My Custom Footer

Join 31,000+ other and never miss out

About

Company

Blog

Tec

Contact

example@email.com

© Brand 2020 - All rights reserved