函数与类
给函数与类补上类型后,调用方会立刻得到参数与返回值提示。
函数注解
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
可选参数与默认值:
function greet(name: string, title?: string) {
return title ? `${title} ${name}` : name;
}
function clamp(n: number, max = 100) {
return Math.min(n, max);
}
函数类型与重载入门
type BinaryOp = (a: number, b: number) => number;
// 重载:同一函数多种调用形态(实现签名要兼容)
function format(x: number): string;
function format(x: string): string;
function format(x: number | string): string {
return String(x);
}
重载适合「参数形态差很多」;简单联合类型往往更清晰。
类
class Counter {
private value = 0;
constructor(public readonly id: string) {}
inc(): number {
this.value += 1;
return this.value;
}
}
const c = new Counter("main");
c.inc();
访问修饰符:public(默认)/ protected / private。参数属性(constructor(public id: string))可少写几行字段声明。
implements
interface Logger {
log(msg: string): void;
}
class ConsoleLogger implements Logger {
log(msg: string) {
console.log(msg);
}
}
implements 检查实例侧是否满足接口,不生成运行时代码。
要点
- 参数、返回值、可选与默认值
- 重载慎用,联合类型优先
- 类字段与访问修饰符
implements只是编译期契约