TypeScript 实用技巧分享


TypeScript 已经成为前端开发的标配,但很多实用技巧容易被忽略。

satisfies 保持类型推断

const theme = {
  primary: '#007bff',
  secondary: '#6c757d',
} satisfies Record<string, string>;

这样既能校验类型,又不会丢失具体的字面量类型。

const 泛型参数

function getConfig<T extends readonly string[]>(keys: T) {
  return keys;
}
const keys = getConfig(['name', 'age'] as const);
// 类型是 readonly ['name', 'age'],不是 string[]

这些小技巧用好了,代码质量和开发体验都能提升不少。