You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否定义引用其他行类型参数的类型以提升TS代码可读性?

能否在接口中定义引用方法泛型参数的内部类型?以Promise为例

标准的Promise接口定义如下:

interface Promise<T> {
  then<TResult1 = T, TResult2 = never>(
    onfulfilled?:
      | ((value: T) => TResult1 | PromiseLike<TResult1>)
      | undefined
      | null,
    onrejected?:
      | ((reason: any) => TResult2 | PromiseLike<TResult2>)
      | undefined
      | null
  ): Promise<TResult1 | TResult2>;

  catch<TResult = never>(
    onrejected?:
      | ((reason: any) => TResult | PromiseLike<TResult>)
      | undefined
      | null
  ): Promise<T | TResult>;
}

你尝试将onfulfilled和onrejected的类型单独抽取出来以提升代码可读性,但直接在接口内部定义type的写法无法编译:

interface Promise<T> {
  type OnFulfilled = 
      | ((value: T) => TResult1 | PromiseLike<TResult1>)
      | undefined
      | null
  type OnRejected =
      | ((reason: any) => TResult2 | PromiseLike<TResult2>)
      | undefined
      | null

  then<TResult1 = T, TResult2 = never>(
    onfulfilled?: OnFulfilled,
    onrejected?: OnRejected
  ): Promise<TResult1 | TResult2>;

  catch<TResult = never>(
    onrejected?: OnRejected
  ): Promise<T | TResult>;
}

问题原因

  1. TypeScript的接口内部不允许定义type类型别名,接口只能包含属性签名、方法签名或嵌套接口,无法直接声明类型别名。
  2. TResult1和TResult2是then方法的方法级泛型参数,接口内部的类型无法直接引用这些仅属于方法的泛型参数。

可行的解决方案

你可以将这些回调类型定义为独立的泛型类型,让它们接收所需的泛型参数,然后在接口方法中使用时传入对应的类型:

// 定义独立的泛型回调类型
type PromiseOnFulfilled<T, TResult1> = 
  | ((value: T) => TResult1 | PromiseLike<TResult1>)
  | undefined
  | null;

type PromiseOnRejected<TResult> = 
  | ((reason: any) => TResult | PromiseLike<TResult>)
  | undefined
  | null;

interface Promise<T> {
  then<TResult1 = T, TResult2 = never>(
    onfulfilled?: PromiseOnFulfilled<T, TResult1>,
    onrejected?: PromiseOnRejected<TResult2>
  ): Promise<TResult1 | TResult2>;

  catch<TResult = never>(
    onrejected?: PromiseOnRejected<TResult>
  ): Promise<T | TResult>;
}

这种写法既实现了类型复用、提升了可读性,又符合TypeScript的语法规则。

内容的提问来源于stack exchange,提问作者Daniel Kaplan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 07:50:14