跳到主要内容

TypeScript高级特性

类型推断

// 自动类型推断
let str = 'hello'; // 推断为 string
let arr = [1, 2, 3]; // 推断为 number[]

// 上下文类型推断
window.addEventListener('click', function(e) {
// e 被推断为 MouseEvent
console.log(e.button);
});

类型守卫

// typeof 守卫
function process(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(2);
}

// instanceof 守卫
class Dog {
bark() {}
}

class Cat {
meow() {}
}

function makeSound(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}

映射类型

// Readonly
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};

// Partial
type Partial<T> = {
[P in keyof T]?: T[P];
};

// Pick
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};

条件类型

type NonNullable<T> = T extends null | undefined ? never : T;

type Extract<T, U> = T extends U ? T : never;

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

装饰器

// 类装饰器
function logger(target: Function) {
console.log(`Class name: ${target.name}`);
}

@logger
class Example {
// ...
}

// 属性装饰器
function validate(target: any, key: string) {
let value = target[key];
Object.defineProperty(target, key, {
get() { return value; },
set(newValue) {
value = newValue;
}
});
}