如何使用TypeScript的新特性?

解读

该问题旨在考察候选人对TypeScript语言演进的掌握程度,以及能否结合实际开发场景灵活运用最新特性。在当前国内互联网企业中,TypeScript已成为前端开发的主流选择,面试官通常关注开发者是否了解TypeScript 4.x版本后的核心新特性,例如装饰器、可辨识联合类型、空值合并运算符等。这些特性不仅涉及语法层面的优化,还与工程化实践、框架集成能力密切相关,需通过具体代码示例体现理解深度。

知识点

  1. 装饰器(Decorators):用于增强类、方法、属性等元数据功能
  2. 可辨识联合类型(Discriminated Unions):结合类型守卫实现更精确的类型判断
  3. 空值合并运算符(??):替代可选链操作符处理null/undefined默认值
  4. Assertion 断言(assert):在类型断言场景中替代as操作符
  5. 元组类型(Tuples):定义固定长度和类型的数组结构
  6. 类型推断增强:在函数参数、解构赋值等场景中提升类型自动识别能力
  7. 类的私有字段(Private Fields):通过#符号实现封装
  8. 函数重载(Overloads):支持多函数签名的类型校验
  9. 类型守卫(Type Guards):通过in、instanceof等关键字缩小类型范围

答案

装饰器应用

// 类装饰器:添加元数据  
@Log  
class Service {  
  constructor(private data: string) {}  
}  

// 方法装饰器:拦截方法调用  
class Calculator {  
  @TrackOperation  
  add(a: number, b: number): number {  
    return a + b;  
  }  
}  

// 属性装饰器:修改属性行为  
class User {  
  @Secure  
  password: string;  
}  

可辨识联合类型

type NotificationType = 'email' | 'sms' | 'wechat';  
interface Notification {  
  type: NotificationType;  
  content: string;  
}  

function handleNotification(notification: Notification): void {  
  if (notification.type === 'email') {  
    console.log('处理邮件通知');  
  } else if (notification.type === 'wechat') {  
    console.log('处理微信通知');  
  }  
}

空值合并与Assertion

// 空值合并运算符  
const config = {  
  timeout: 3000 ?? 5000,  
  env: process.env.NODE_ENV ?? 'development'  
};  

// Assertion断言  
const value = getValue();  
const assertedValue = assert(value, 'value must be defined');  

元组类型与类型推断

// 元组类型  
const coordinates: [number, number] = [100, 200];  

// 类型推断增强(函数参数)  
function processData(data: string[]): void {  
  const [first, ...rest] = data;  
  console.log(first, rest);  
}  

私有字段与函数重载

// 私有字段  
class Counter {  
  #count = 0;  
  increment() {  
    this.#count++;  
  }  
}  

// 函数重载  
function parse(input: string): string[];  
function parse(input: string[]): string[];  
function parse(input: string | string[]): string[] {  
  return Array.isArray(input) ? input : input.split('');  
}

拓展思考

  1. 工程化实践:在大型项目中,如何通过装饰器实现组件自动注册?例如在Vue3中使用@Component装饰器简化组件定义
  2. 类型守卫组合:当处理复杂嵌套对象时,如何结合in操作符和类型谓词函数构建多层类型校验?
  3. 版本兼容性:TypeScript 4.1引入的--strict模式如何与ES模块规范结合使用?需注意import语句的类型注解配置
  4. 性能优化:在React函数组件中,如何利用React.memo与类型守卫减少不必要的渲染?
  5. 类型推断边界:当使用const [a, b] = ...解构时,如何通过类型断言或类型守卫处理可能的类型错误?