勉強日記

チラ裏

Programming TypeScript ch1-2

www.oreilly.com


Introduction

  • 型安全
    • using types to prevent programs from doing invalid things.
  • invalidってなに
    • numberとリストの掛け算とか
  • 実行する前に、テストする前にわかるのが強い

TypeScript: A 10,000 Foot View

The Compiler

The Type System

  • 型システムは2つに大別される
    • 明示
    • 推論
  • これらはトレードオフ
  • TSは両方にインスパイアされている
    • 明示もできるし推論させることもできる
  • 型の明示は最小限にしたほうがいい

TypeScript Versus JavaScript

How are types bound?

  • TS: gradually typed language (漸進的型付け)
  • 全てが静的に型付けされていなくてもコンパイルが通る
    • 型が与えられていない部分では間違いを見逃すことがある
  • レガシーなJSコードからTSに漸進的に移行するときに有用
  • ただし、そうでないならば型カバレッジ100%を目指すべき

Are types automatically converted?

  • 明示的に変換せよ

When are types checked?

when are errors surfaced?

  • コンパイル時エラー
  • 実行時エラー
    • スタックオーバーフロー
    • ネットワークコネクションエラー
    • ユーザー入力不正
  • 全部実行時エラーなpure JSより良い

Code Editor Setup

npm init -y
npm install --save-dev typescript tslint @types/node

tsconfig.json

  • 雛形tsconfig.json生成できたりする
npx tsc --init
  • 今回はこうする
{
  "compilerOptions": {
    "lib": ["es2015"],
    "module": "commonjs",
    "outDir": "dist",
    "sourceMap": true,
    "strict": true,
    "target": "es2015"
  },
  "include": [
    "src"
  ]
}
  • ブラウザならlib"dom"を追加したりする

tslint.json

  • 雛形生成
npx tslint --init
{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {},
    "rulesDirectory": []
}
  • 今回はこうしてみる
{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended"
  ],
  "rules": {
    "semicolon": [true, "never"],
    "trailing-comma": [true, "always"]
  }
}
npx tslint -c tslint.json './src/**/*.ts'

index.ts

console.log('Hello TypeScript!')
npx tsc
node ./dist/index.js
Hello TypeScript!

shortcuts

  • ts-node でTSを直接実行
  • typescript-node-starter でスキャフォールディング

英語

  • feed up
    • うんざりする
  • getting warm
    • 核心に近づく