" />
本ページはプロモーションが含まれています。

スポンサーリンク

TypeScript

TypeScript入門~型・環境構築~

TypeScriptについて

TypeScriptの型システム

TypeScriptは漸進的型付き言語であり、コンパイル時に型安全性がチェックされるが、コンパイル時に全ての型がわかっている(記述されている)必要はない。
しかし基本的には、100%の型指定を目指すべきである。

型はアノテーションで指示する。
アノテーションは「値:型」の形式をとる。

let a: number = 1
let b: string = 'hello'
let c: boolean[] = [true, false]

TypeScriptはC#から影響を受けている。(Javaではない)

TypeScriptの型とは?

型とは、値とその値を使ってできる事柄の集まりである。
他のオブジェクト指向言語を使った人は、クラスと同義と考えて良い。
Javaで言うと型=クラスであり、クラスとはフィールド(値)とメソッド(その値を使ってできる事柄)である。

TypeScriptプロジェクの始め方

依存モジュールを追加

ts1 % npm init
ts1 % npm i -D typescript tslint @types/node

ts1 % ./node_modules/.bin/tsc -v
Version 4.5.4
  • typescript はTSC
  • tslint はTypeScript用のリンター
  • @types/node はNode.js用の型宣言

任意のプロジェクトディレクトリ直下で上記を実行する。

tsconfig.jsonを記述する

TypeScriptのプロジェクトは必ずプロジェクトルートにtsconfig.jsonが必要である。

項目の説明

{
  "compilerOptions": {
    "lib": ["es2015"],
    "module": "commonjs",
    "outDir": "dist",
    "sourceMap": true,
    "strict": true,
    "target": "es2015",
  },
  "include": [
    "src"
  ]
}
includeソースファイルの置き場所。TSCがソースを探しにいくパス。
libコンパイル時にどの型宣言ライブラリを読み込んでおくか。
例)document.createElement()を使うには、"DOM"のlibが必要である。
moduleどのモジュールシステムにコンパイルするか。
CommonJS、SystemJS、ES2015など
outDirどのディレクトリにコンパイルしたJavaScriptコードを出力するか。
strictコードチェックを厳格にチェックするか。
常にtrueを推奨する。
targetどのバージョンのJavaScriptコードを出力するか?
ES3、ES5、ES2015、ES2016など

JavaScriptの歴史

発表年ECMAScriptESyyyyESn
~2008ES5
2009ES5.1
2015ECMA-262 edition 6ES2015ES6クラスやアロー関数、let/const、import/exportが追加された。
2015年に発表されたES2015(=ES6)は重要なので覚えておこう。

TypeScriptを実行する

TypeScriptはTSCというコンパイラによって、JavaScriptに変換される。
TSCを実行するにはNode.jsが必要である。

TypeScriptの組込みの型

これらの組み込みの型はアノテーションで指定しなくても、TypeScriptが型推論を行なってくれる。
また、組み込みの型の型名は小文字で始まる。

Any型

Any型は何にでも使えるが、使うべきではない。
Any型を使うならTypeScriptを使う意味がない。

プリミティブ型

number2^53までを表現できる。(9007199254740991 ~ -9007199254740991)
数を扱う場合はほとんどこの型で良い。
string任意の文字列を扱える。
booleantrue or false をとりうる。
0 や 1 はnumber型のため、booleanに代入することはできない。
let a = true;
const b = false;

let num1 = 9007199254740991;
const num2 = -9007199254740991;

let str1 = "あいうえお";
const str2 = "アイウエオ";

これらの型は、TypeScriptに型を推論させることができる。

let boo3: boolean = true;
let num3: number = 123;
let str3: string = "aiueo";

このようにアノテーションで型指定しても良いが、上で紹介したTypeScriptに型を推論させた方が良い。

string型はバッククォートで囲むことで、改行した文字列を扱うことができる。

配列型

配列は次のように宣言する。

let arrayA = [1, 2, 3];
let arrayB: number[] = [2, 3, 4];
let arrayC: Array<number> = [3, 4, 5];

BとCは記法は違うが、全く同じ配列型を指す。
TypeScriptにおいて意味的・パフォーマンス的に完全に同一である。
基本的にはBの書き方で良いが、TypeScriptに要素の型を推論させているAを推奨する。

タプル型

タプルは配列型の派生型である。
配列と違い、要素の数と各要素の型を指定する必要がある。

let tuppleA: [string, string, number] = ["液晶ビエラ", "Sony", 120000];
let tuppleC: [string, number, boolean] = ["液晶ビエラ", 120000, false];

列挙型(enum型)

列挙した要素にstring、numberを割り当てることができる。

enum Country {
  Japan = "日本",
  China = "中国",
  Korea = 123,
}

console.log(Country.Japan); // => 日本

null,undefined,void,naver型

null値が欠如している状態を表す。
undifinedまだ定義されていない状態を表す。
void関数の戻り値の型にのみ使用する。
関数は終了するが、何も返さないことを表す。
例)console.logの実行のみなど
naver関数の戻り値の型にのみ使用する。
関数が決して終了しないことを表す。
例)while(true)により無限ループをする関数
例)最後にErrorをスローする関数など。

ESLintの設定

TSLintは2019年をもって非推奨となっため、ESLintのTypeScriptプラグインを使うこと。

ESLintパッケージのインストール

ts1 % yarn add -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser

ts1 % ./node_modules/.bin/eslint -v    
v8.5.0
  • eslint...ESLint本体。
  • @typescript-eslint/eslint-plugin...ESLintのTypeScript用プラグイン。
  • @typescript-eslint/parser...TypeScriptをESLint向けにパースする。

設定ファイル.eslintrc.jsを作成

方法は手動で.eslintrc.jsを作成する方法と、コマンドで作成する方法がある。

コマンドでは対話的に.eslintrc.jsを作成できる。

ts1 % ./node_modules/.bin/eslint --init
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · google
✔ What format do you want your config file to be in? · JavaScript
Checking peerDependencies of eslint-config-google@latest
The config that you've selected requires the following dependencies:

@typescript-eslint/eslint-plugin@latest eslint-config-google@latest eslint@>=5.16.0 @typescript-eslint/parser@latest
✔ Would you like to install them now with npm? · No / Yes
Installing @typescript-eslint/eslint-plugin@latest, eslint-config-google@latest, eslint@>=5.16.0, @typescript-eslint/parser@latest
npm WARN ts1@1.0.0 No description
npm WARN ts1@1.0.0 No repository field.

+ eslint-config-google@0.14.0
+ eslint@8.5.0
+ @typescript-eslint/parser@5.8.1
+ @typescript-eslint/eslint-plugin@5.8.1
removed 2 packages, updated 4 packages and audited 161 packages in 10.241s

6 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Successfully created .eslintrc.js file in /Users/noricgeographic/repositories/sandbox/ts1

ts1 % cat .eslintrc.js 
module.exports = {
  'env': {
    'browser': true,
    'es2021': true,
  },
  'extends': [
    'google',
  ],
  'parser': '@typescript-eslint/parser',
  'parserOptions': {
    'ecmaVersion': 13,
    'sourceType': 'module',
  },
  'plugins': [
    '@typescript-eslint',
  ],
  'rules': {
  },
};

オライリー「プログラミング TypeScript」で紹介されているオススメ設定はこちら。

module.exports = {
  'root': true,
  'parser': '@typescript-eslint/parser',
  'parserOptions': {
    'project': './tscofing.json',
  },
  'plugins': [
    '@typescript-eslint',
  ],
  'extends': [
    'eslint:recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
};

ESLintを実行する

TypeScriptコンパイル時のエラー

TS7006: Parameter 'n' implicitly has an 'any' type.

TS7006: Parameter 'n' implicitly has an 'any' type.

1 function squareOf(n) {
                    ~

指示されている箇所が暗黙のうちに(implicitly)Any型になっている。
TypeScriptなので、型を指定してあげよう。

TS5024: Compiler option 'sourceMap' requires a value of type boolean.

TS5024: Compiler option 'sourceMap' requires a value of type boolean.

6     "sourceMap": "true",
                   ~~~~~~

エラーに出ているtsconfig.jsonの項目はboolean型である必要がある。
上記の例では”true”ではなく、単にtrue。

TS18003: No inputs were found

error TS18003: No inputs were found in config file '/Users/noricgeographic/repositories/sandbox/ts1/tsconfig.json'. Specified 'include' paths were '["src"]' and 'exclude' paths were '["dist"]'.

tsconfig.jsonのincludeで指定される場所に、コンパイルすべきファイルが1つもない。

スポンサーリンク

-TypeScript