【TypeScript】TypeScriptで変数の型を宣言する

TypeScript

1. 概要

こちらのTypeScriptのTutorialを、コード中心に書いていきます。

  • 変数の型を宣言
  • TypeScriptとコンパイルされたJavaScriptを見比べながら見て下さい。

2. TypeScriptのコンパイラをインストール

2-1. こちらを参考

3. tsconfig.json を生成 + 修正

3-1. こちらを参考

4. TypeScriptの型とサブタイプ

TypeScript での型の概要 – Training | Microsoft Learn

5. コードを書いて確認

5-1. サンプルコード1

  • module02-1.ts
// [Type] boolean
let flag: boolean;
let yes = true;
let no = false;

// [Type] number, biginteger
let x: number;
let y = 0;
let z: number = 123.456;
let big: bigint = 100n;

// [Type] string
let s: string;
let empty = "";
let abc = 'abc';

let firstname: string = "Mateo";
let sentence: string = `My name is ${firstname}.
    I am new to TypeScript.`;
console.log(sentence);
  • コンパイル
    • tsv
  • build/module02-1.js
"use strict";
// [Type] boolean
let flag;
let yes = true;
let no = false;
// [Type] number, biginteger
let x;
let y = 0;
let z = 123.456;
let big = 100n;
// [Type] string
let s;
let empty = "";
let abc = 'abc';
let firstname = "Mateo";
let sentence = `My name is ${firstname}.
    I am new to TypeScript.`;
console.log(sentence);
  • 実行
    • node build/module02-1.js
  • 実行結果
My name is Mateo.
    I am new to TypeScript.

5-2. サンプルコード2

  • module02-2.ts
// [Type] enum
enum ContractStatus {
    Permanent,
    Temp,
    Apprentice
}
let employeeStatus: ContractStatus = ContractStatus.Temp;
console.log(employeeStatus);
console.log(ContractStatus[employeeStatus]);

enum ContractStatusWithDefaultValue {
    Permanent = 1,
    Temp,
    Apprentice
}
let employeeStatusWithDefaultValue: ContractStatusWithDefaultValue = ContractStatusWithDefaultValue.Temp;
console.log(employeeStatusWithDefaultValue);
console.log(ContractStatusWithDefaultValue[employeeStatusWithDefaultValue]);
  • コンパイル
    • tsv
  • build/module02-2.js
"use strict";
// [Type] enum
var ContractStatus;
(function (ContractStatus) {
    ContractStatus[ContractStatus["Permanent"] = 0] = "Permanent";
    ContractStatus[ContractStatus["Temp"] = 1] = "Temp";
    ContractStatus[ContractStatus["Apprentice"] = 2] = "Apprentice";
})(ContractStatus || (ContractStatus = {}));
let employeeStatus = ContractStatus.Temp;
console.log(employeeStatus);
console.log(ContractStatus[employeeStatus]);
var ContractStatusWithDefaultValue;
(function (ContractStatusWithDefaultValue) {
    ContractStatusWithDefaultValue[ContractStatusWithDefaultValue["Permanent"] = 1] = "Permanent";
    ContractStatusWithDefaultValue[ContractStatusWithDefaultValue["Temp"] = 2] = "Temp";
    ContractStatusWithDefaultValue[ContractStatusWithDefaultValue["Apprentice"] = 3] = "Apprentice";
})(ContractStatusWithDefaultValue || (ContractStatusWithDefaultValue = {}));
let employeeStatusWithDefaultValue = ContractStatusWithDefaultValue.Temp;
console.log(employeeStatusWithDefaultValue);
console.log(ContractStatusWithDefaultValue[employeeStatusWithDefaultValue]);
  • 実行
    • node build/module02-2.js
  • 実行結果
1
Temp
2
Temp

5-3. サンプルコード3

  • module02-3.ts
// [Type] any
let anyValue: any = 10;
anyValue = 'Mateo';
anyValue = true;
console.log(anyValue); // OK
console.log(anyValue.name); // undefined
// anyValue(); // TypeError: anyValue is not a function
// anyValue.toUpperCase(); // TypeError: anyValue.toUpperCase is not a function

// [Type] unknown
let unknownValue: unknown = 10;
unknownValue = true;
unknownValue = 'Mateo';
console.log(unknownValue); // OK
// console.log(unknownValue.name); // error: 'unknownValue' is of type 'unknown'.
// unknownValue(); // error: 'unknownValue' is of type 'unknown'.
// unknownValue.toUpperCase(); // error: 'unknownValue' is of type 'unknown'.

// Type Assertion
let assertionValue: unknown = 10;
assertionValue = true;
assertionValue = 'Mateo';
if (typeof assertionValue === "string") { // Type Guard
    console.log((assertionValue as string).toUpperCase());
} else if (typeof assertionValue === "number") { // Type Guard
    console.log(`${assertionValue} is number`);
} else if (typeof assertionValue === "boolean") { // Type Guard
    console.log(`${assertionValue} is boolean`);
} else if (typeof anyValue.name === "undefined") { // Type Guard
    console.log(`${assertionValue} is undefined`);
} else if (typeof assertionValue === "function") { // Type Guard
    console.log(`${assertionValue} is function`);
} else if (Array.isArray(assertionValue)) { // Type Guard
    console.log(`${assertionValue} is array`);
} else {
    console.log('Error - No case.');
}
  • コンパイル
    • tsv
  • build/module02-3.js
"use strict";
// [Type] any
let anyValue = 10;
anyValue = 'Mateo';
anyValue = true;
console.log(anyValue); // OK
console.log(anyValue.name); // undefined
// anyValue(); // TypeError: anyValue is not a function
// anyValue.toUpperCase(); // TypeError: anyValue.toUpperCase is not a function
// [Type] unknown
let unknownValue = 10;
unknownValue = true;
unknownValue = 'Mateo';
console.log(unknownValue); // OK
// console.log(unknownValue.name); // error: 'unknownValue' is of type 'unknown'.
// unknownValue(); // error: 'unknownValue' is of type 'unknown'.
// unknownValue.toUpperCase(); // error: 'unknownValue' is of type 'unknown'.
// Type Assertion
let assertionValue = 10;
assertionValue = true;
assertionValue = 'Mateo';
if (typeof assertionValue === "string") { // Type Guard
    console.log(assertionValue.toUpperCase());
}
else if (typeof assertionValue === "number") { // Type Guard
    console.log(`${assertionValue} is number`);
}
else if (typeof assertionValue === "boolean") { // Type Guard
    console.log(`${assertionValue} is boolean`);
}
else if (typeof anyValue.name === "undefined") { // Type Guard
    console.log(`${assertionValue} is undefined`);
}
else if (typeof assertionValue === "function") { // Type Guard
    console.log(`${assertionValue} is function`);
}
else if (Array.isArray(assertionValue)) { // Type Guard
    console.log(`${assertionValue} is array`);
}
else {
    console.log('Error - No case.');
}
  • 実行
    • node build/module02-3.js
  • 実行結果
true
undefined
Mateo
MATEO

5-4. サンプルコード4

  • module02-4.ts
// [Type] Union
let multiType: number | boolean;
multiType = 20;
multiType = true;
// multiType = 'twenty'; // Invalid

const add = (x: number | string, y: number | string) => {
    if (typeof x === 'number' && typeof y === 'number') {
        return x + y;
    }
    if (typeof x === 'string' && typeof y === 'string') {
        return x.concat(y);
    }
    throw new Error('Parameters must be numbers or strings.');
}
console.log(add('one', 'two'));
console.log(add(1, 2));
// console.log(add('one', 2)); // returns error

// [Type] Intersection
interface Employee {
    employeeID: number;
    age: number;
}
interface Manager {
    stockPlan: boolean;
}
type ManagementEmployee = Employee & Manager;
let newManager: ManagementEmployee = {
    employeeID: 12345,
    age: 34,
    stockPlan: true
};
console.log(newManager);

// [Type] Literal
type testResult = "pass" | "fail" | "incomplete";
let myResult: testResult;
myResult = "incomplete";
myResult = "pass";
// myResult = "failure"; // Invalid
console.log(myResult);

type dice = 1 | 2 | 3 | 4 | 5 | 6;
let diceRoll: dice;
diceRoll = 1;
diceRoll = 4;
// diceRoll = 7; // Invalid
console.log(diceRoll);
  • コンパイル
    • tsv
  • build/module02-4.js
"use strict";
// [Type] Union
let multiType;
multiType = 20;
multiType = true;
// multiType = 'twenty'; // Invalid
const add = (x, y) => {
    if (typeof x === 'number' && typeof y === 'number') {
        return x + y;
    }
    if (typeof x === 'string' && typeof y === 'string') {
        return x.concat(y);
    }
    throw new Error('Parameters must be numbers or strings.');
};
console.log(add('one', 'two'));
console.log(add(1, 2));
let newManager = {
    employeeID: 12345,
    age: 34,
    stockPlan: true
};
console.log(newManager);
let myResult;
myResult = "incomplete";
myResult = "pass";
// myResult = "failure"; // Invalid
console.log(myResult);
let diceRoll;
diceRoll = 1;
diceRoll = 4;
// diceRoll = 7; // Invalid
console.log(diceRoll);
  • 実行
    • node build/module02-4.js
  • 実行結果
onetwo
3
{ employeeID: 12345, age: 34, stockPlan: true }
pass
4

5-5. サンプルコード5

  • module02-5.ts
// [Type] Arrays
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
console.log(list1);
console.log(list2);

// [Type] Tuples
let person1: [string, number] = ['Marcia', 35];
let person2: [string, number, boolean] = ['Marcia', 35, true];
// let person3: [string, number] = [35, 'Marcia']; // Invalid
console.log(person1);
console.log(person2);
  • コンパイル
    • tsv
  • build/module02-5.js
"use strict";
// [Type] Arrays
let list1 = [1, 2, 3];
let list2 = [1, 2, 3];
console.log(list1);
console.log(list2);
// [Type] Tuples
let person1 = ['Marcia', 35];
let person2 = ['Marcia', 35, true];
// let person3: [string, number] = [35, 'Marcia']; // Invalid
console.log(person1);
console.log(person2);
  • 実行
    • node build/module02-5.js
  • 実行結果
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 'Marcia', 35 ]
[ 'Marcia', 35, true ]

ディレクトリ構成

tree
.
├── build
│   ├── module02-1.js
│   ├── module02-2.js
│   ├── module02-3.js
│   ├── module02-4.js
│   └── module02-5.js
├── module02-1.ts
├── module02-2.ts
├── module02-3.ts
├── module02-4.ts
├── module02-5.ts
└── tsconfig.json

1 directory, 11 files

6. 備考

変数名だけでは伝わり切れない場合

型を指定しておくと、チームメンバーにはやさしい説明になりますね。

7. 参考

投稿者プロフィール

Sondon
開発好きなシステムエンジニアです。
卓球にハマってます。

関連記事

  1. 【React】FullCalendarのカレンダーを整えるためのTip…

  2. 【React】FullCalendarを使用してカレンダーを表示するた…

  3. TypeScript

    【TypeScript】Vitestを使ってみる

  4. TypeScript

    【TypeScript】インターフェイスの実装

  5. 【React】FullCalendarのカレンダーにイベントを表示する…

  6. TypeScript

    【TypeScript】触ってみる

最近の記事

制作実績一覧

  1. Checkeys