interface (接口) 和 type (类型别名) 有什么区别?应该如何选择?

  • 共同点:都可以定义对象形状。
  • interface 特点:声明合并、可继承 (extends)、可被类实现 (implements)。主要用于定义对象/类结构契约。
  • type 特点:更灵活,可以为任何类型创建别名(联合、交叉、元组、原始类型等),不能声明合并,通常用于定义联合/交叉类型或使用高级类型。
  • 选择:定义公共 API 或期望被扩展用 interface,定义联合/交叉类型或简单类型别名用 type,应用内部对象两者皆可,看团队规范。

any, unknown

  • any:任意类型,关闭类型检查(应避免使用)。
  • unknown:类型未知,是 any 的类型安全版本,使用前需要进行类型检查或断言。

高级类型

type Partial<T> = {
    [P in keyof T]?: T[P];
};
 
type Required<T> = {
    [P in keyof T]-?: T[P];
};
 
/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
 
/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
 
/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
 
/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;
 
/**
 * Extract from T those types that are assignable to U
 */
type Extract<T, U> = T extends U ? T : never;
 
/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
 
 
/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
 
/**
 * Obtain the return type of a function type
 */
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
 
 
/**
 * Obtain the return type of a constructor function type
 */
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;