TypeScript为何需要定义比较复杂的泛型类型?

作者站长头像
站长
· 阅读数 14

有看到过定义比较复杂的泛型类型:

/** A complex generic type. */
export type ComplexGenericTypeAlias<T> =
    | T
    | T[]
    | Promise<T>
    | Promise<T[]>
    | Record<string, Promise<T>>;

请问下,为何需要定义这么多或的Type呢?

为何不直接定义:

type AAA<T> = T
type BBB<T> = T[]
type CCC<T> = Promise<T>
...

为何需要把这些风马牛不相及的类型(T, Promise, Record)组在一起?

回复
1个回答
avatar
test
2024-09-07

为了complexGenericTypeAlias这个函数的返回值,不然按你直接这么定义,返回值不方便写

type AAA<T> = T
type BBB<T> = T[]
type CCC<T> = Promise<T>
/** A complex generic type. */
export type ComplexGenericTypeAlias<T> =
    | T
    | T[]
    | Promise<T>
    | Promise<T[]>
    | Record<string, Promise<T>>;

function complexGenericTypeAlias<T>(value: T): ComplexGenericTypeAlias<T>  {
    if (value === 'array') {
        return [value]
    }
    if (value === 'promise') {
        return Promise.resolve(value)
    }
    if (value === 'promiseArray') {
        return Promise.resolve([value])
    }
    if (value === 'promiseRecord') {
        return { key: Promise.resolve(value) }
    }
    return value
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容