TypeScript为何需要定义比较复杂的泛型类型?-灵析社区

WhatUpDanger

有看到过定义比较复杂的泛型类型: /** A complex generic type. */ export type ComplexGenericTypeAlias = | T | T[] | Promise | Promise | Record>; 请问下,为何需要定义这么多或的Type呢? 为何不直接定义: type AAA = T type BBB = T[] type CCC = Promise ... 为何需要把这些风马牛不相及的类型(`T, Promise, Record`)组在一起?

阅读量:131

点赞量:0

问AI
为了"complexGenericTypeAlias"这个函数的返回值, 不然按你直接这么定义,返回值不方便写 type AAA = T type BBB = T[] type CCC = Promise /** A complex generic type. */ export type ComplexGenericTypeAlias = | T | T[] | Promise | Promise | Record>; function complexGenericTypeAlias(value: T): ComplexGenericTypeAlias { 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 }