TypeScript's syntax is JavaScript's syntax. What it adds is a way to describe the types of variables, parameters, and return values. This chapter covers declarations, functions, arrow functions, and control flow, along with a practical rule of thumb for when to write types yourself and when to let the compiler infer them.
let and const
Declare variables with let or const. A const binding cannot be reassigned; a let binding can. Both are block-scoped, meaning they only exist inside the nearest pair of braces. The legacy var keyword is function-scoped and full of surprises, so leave it out of new code.
const appName = "TASTEDEV"; // cannot be reassigned
let count = 0; // can change
count += 1;
const user = { name: "Kim", age: 30 };
user.age = 31; // fine: properties are still mutable
// user = { name: "Lee", age: 20 }; // error: cannot assign to a const
if (count > 0) {
const inner = "only visible inside this block";
console.log(inner);
}
Note that const locks the binding, not the object it points to. A good default is to reach for const everywhere and switch to let only when a value genuinely needs to change. Readers then know at a glance which names can move.
Annotations and inference
Writing : Type after a name is a type annotation. Most of the time you can skip it, because TypeScript infers the type from the initial value.
let title: string = "Guide"; // annotated, but redundant
let pages = 120; // inferred as number
const lang = "en"; // inferred as the literal type "en"
let total: number; // no initializer, so annotate
total = pages * 2;
// pages = "many"; // error: string is not assignable to number
Because pages is a let, it gets the wide type number. lang is a const that can never change, so its type is the exact value "en". That is called a literal type, and it becomes important in chapters 3 and 6.
Places where an explicit annotation pays off:
- Function parameters. There is nothing to infer from, so always annotate them.
- Return types of exported functions. They act as a contract and stop accidental changes.
- Variables declared without a value, and empty arrays you fill in later.
Functions
Annotate each parameter, and optionally the return type after the parameter list. Mark a parameter optional with ?, or give it a default value.
function add(a: number, b: number): number {
return a + b;
}
function formatName(first: string, last?: string): string {
return last ? `${first} ${last}` : first;
}
function repeat(text: string, times = 2): string {
return text.repeat(times); // times is inferred as number
}
function sum(...values: number[]): number {
return values.reduce((acc, v) => acc + v, 0);
}
function log(message: string): void {
console.log(message); // no return value, so void
}
add(1, 2); // 3
formatName("Ada"); // "Ada"
sum(1, 2, 3, 4); // 10
コメント 0件
ログイン · ログインするとコメントできます。