【发布时间】:2021-07-26 19:45:44
【问题描述】:
如果输入参数是数组类型,我正在尝试键入一个应该返回数组类型的函数,否则返回一个普通参数。这是我的尝试:
function test<T extends number|number[]>(a: T):T extends number[] ? string[] : string {
if (Array.isArray(a)) {
return ['123', '45']
}
return '123'
}
我在返回语句中收到错误:Type 'string' is not assignable to type 'T extends number[] ? string[] : string'.
我正在寻找的是以下内容:
const a = test(3) // "a" is string type
const b = test([1,2,3]) // "b" is string[] type
【问题讨论】:
标签: typescript typescript-generics