読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
①で作った計算のコードを、.ts のファイルに移します。
type Product = {
id: string;
name: string;
price: number;
};
const bread: Product = { id: "p001", name: "食パン(1斤)", price: 380 };
const croissant: Product = { id: "p002", name: "クロワッサン", price: 220 };
const products: Product[] = [bread, croissant];
const calcSubtotal = (price: number, quantity: number): number => price * quantity;
const formatYen = (amount: number): string => `${amount}円`;
console.log(formatYen(calcSubtotal(croissant.price, 2)));
// "440円"
| 書いた型 | 意味 |
|---|---|
type Product = { ... } | 商品のデータの形に名前を付ける |
Product[] | 商品の配列 |
(price: number, quantity: number) | 引数は2つとも数 |
: number、: string | 戻り値の型 |
JavaScript のコードに型を足しただけで、処理の中身は変わっていません。TypeScript は JavaScript に型を書き足した言語なので、JavaScript の書き方はそのまま使えます。
16 / 18