【发布时间】:2021-02-21 03:26:25
【问题描述】:
我将展示几个 with 和 without 泛型返回类型的示例,我很困惑为什么 typescript 不处理所有示例一样。
示例 1:基本情况 - 函数重载(正常工作)
function test(data:string):string
function test(data:string[]):string[]
function test(data:string | string[]): string | string[] {
if(Array.isArray(data)){
return ['']
}
return data
}
const testArr = test([]) // return type is Array
const testStr=test('a') // return type is string
现在我将尝试对 generic 数据类型做同样的事情:
示例 2:从函数推断的返回类型错误
function testGeneric<T extends string | string[]>(data:T){
if(Array.isArray(data)){
return ['']
}
return data
}
const testArrGen = testGeneric([])
const testStrGen=testGeneric('a')
示例 3:函数本身的返回类型错误。
function testGeneric2<T extends string | string[]>(data:T): T extends string? T : T[]{
if(Array.isArray(data)){
return [''] // error
}
return data // error
}
const testArrGen2 = testGeneric2([]) // string[] || never[]
const testStrGen2=testGeneric2('a') // "a"| string[]
现在我想了解为什么示例 2 和 3 是错误的,以及如何使用泛型创建正确的实现。
【问题讨论】:
-
this 回答你的问题了吗?
标签: typescript