Make it to make it

いろいろ作ってアウトプットするブログ

TypeScript学習1(Type annotations, Type inference)

重要な概念を2つほど。

Type annotations / Type inference

Type annotations

Code we add to tell TypeScript what type of value a variable will refer to

Type inference

TypeScript tries to figure out what type of value a variable refers to

前者はコードでTSに明示的に型付けをさせているのに対して、 後者はTS側で型付けを自動的に行っているというものである。

Type annotations

アノテーションの一例を以下に示す。

// Basic primitives
const apples: number = 5;
const speed: string = 'fast';
const hasName: boolean = true;
const nothingMuch: null = null;
const nothing: undefined = undefined;

// Built-in objects
const now: Date = new Date();

// Array
const colors: string[] = ['red', 'green', 'blue'];
const myNumbers: number[] = [1, 2, 3];
const truths: boolean[] = [true, true];

// Classes
class Car {}
const car: Car = new Car();

// Object literal
const point: { x: number; y: number } = {
  x: 10,
  y: 20
};

// Function
const logNumber: (i: number) => void = (i: number) => {
  console.log(i);
};
// : (i: number) => void  Description of a function

ここまで例を述べてきたが、実は上記の型アノテーションの記述は全て除却しても全く同様にはたらく。 なぜかというと、TS側で全ての型について当ててくれるから。

Type inference

宣言と初期化が同じ行に存在すれば、TS側で勝手に型を割り当ててくれるというもの。

const color = 'red';  // variable declaration = variable initialization

なので、必ず同じ行に宣言と初期化を行うこと。

使い分け

Type annotations

  • 変数宣言を行い、違う行で初期化を行う場合
  • TSの方で自動的に型の割当を行えないという場合
  • ファンクションがany型を返却し、値を明確にしないといけない場合
  • anyになってしまう場合(TSでのチェックを通過してしまう場合)

anyになってしまうことをtype annotationsを記述することで避ける!

string JSON.parse()
'false' boolean
'4' number
'{ "value": 5 }' {value: number}
'{ "name": "alex" }' {name: string}
// When to use annotations
// 1) Function that returns the 'any' type
const json = '{"x": 10, "y": 20}';
const coords: { x: number; y: number } = JSON.parse(json);
console.log(coords);

// 2) When we declare a variable on one line and initialize it later
let words = ['red', 'green', 'blue'];
let foundWord: boolean; // or just use `let foundWord = false`

for (let i = 0; i < words.length; i++) {
  if (words[i] === 'green') {
    foundWord = true;
  }
}

// 3) Variables whose type cannot be inferred correctly
let numbers = [-10, -1, 12];
let numberAboveZero: boolean | number = false;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 0) {
    numberAboveZero = numbers[i];
    console.log(numberAboveZero);
  }
}

Type inference

上記以外は、ほとんどこちらを使うことになる。

まとめ

Type inferenceはconst的に常に使い、それ以外の場合はletを使うような要領でType annotationsを使う。