読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第3節 型推論

3.2 const と let で型が変わる

shopName の型が string ではなく "こもれびベーカリー" になったのは、const で作ったためです。

const fixedCategory = "bread";
// 型は "bread"

let currentCategory = "bread";
// 型は string
作り方推論される型理由
constリテラル型("bread")あとから値が変わらない
let広い型(string)あとで別の文字列を入れるかもしれない

この違いは、リテラル型の変数に値を渡すときに効いてきます。

type ProductCategory = "bread" | "pastry" | "savory" | "sweets";

const showCategory = (category: ProductCategory) => {
  console.log(category);
};

let currentCategory = "bread";
showCategory(currentCategory);
Argument of type 'string' is not assignable to parameter of type 'ProductCategory'.

currentCategory は string と推論されているので、4つのどれかしか受け取らない関数には渡せません。let currentCategory: ProductCategory = "bread"; と型を書くか、値を変えないなら const にすると直ります。

11 / 17