読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
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