已发布·持续改进
TypeScript 指南 · 2/6
本章目前仅提供英文版。
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.
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.
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 numberBecause 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:
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); // 10Unlike plain JavaScript, TypeScript checks the number of arguments too. Calling add(1) is an error; if a parameter may be omitted, say so with ? or a default.
Arrow functions are compact and do not bind their own this, which makes them ideal for callbacks. When you pass an arrow function as a callback, its parameter types are inferred from context, so you rarely need to annotate them.
const square = (n: number): number => n * n;
const toUpper = (s: string) => s.toUpperCase(); // return type inferred
const scores = [72, 95, 88];
const passed = scores.filter((score) => score >= 80); // score: number
const labels = scores.map((score, index) => `#${index + 1}: ${score}`);
type Comparator = (a: number, b: number) => number;
const ascending: Comparator = (a, b) => a - b;
console.log([...scores].sort(ascending));Naming a function shape, as Comparator does here, lets you reuse the same signature across many functions.
Conditionals and loops work exactly as in JavaScript. Use === and !== for comparisons; they never coerce types behind your back.
function grade(score: number): string {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
}
return "C";
}
function dayName(day: number): string {
switch (day) {
case 0: return "Sunday";
case 6: return "Saturday";
default: return "Weekday";
}
}
const fruits = ["apple", "pear", "persimmon"];
for (const fruit of fruits) {
console.log(fruit); // iterates over values
}
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
let n = 3;
while (n > 0) {
n--;
}
const status = n === 0 ? "done" : "running";For arrays, for...of is the most readable loop. Avoid for...in on arrays: it walks over keys as strings, not values.
const, use let when a value must change, and skip var.?, defaults with =, and rest parameters with ....===, and loop over arrays with for...of.
0 条评论
登录 · 登录后即可发表评论。
来发表第一条评论吧。