typescript - 通用条件返回类型
问题描述
我试图通过测试函数的通用参数来推断返回结果。return
我在声明中遇到错误。但是,当使用函数时,返回结果是正确推断的。
function arrayTest<T extends string | string[]>(
data: T
): T extends string[] ? string[] : string | undefined {
if(Array.isArray(data)){
return data
}
else{
return Math.random() > 0.5 ? data : undefined
}
}
const arr = arrayTest(['a']) // correctly infers array
const str = arrayTest('a') // infers string
Type 'T' is not assignable to type 'T extends string[] ? string[] : string | undefined'.
Type 'string | string[]' is not assignable to type 'T extends string[] ? string[] : string | undefined'.
Type 'string' is not assignable to type 'T extends string[] ? string[] : string | undefined
解决方案
看起来还不支持TypeScript
从输入类型推断返回类型。同时,您可以改用函数重载
function arrayTest(
data: string
): string
function arrayTest(
data: string[]
): string[]
function arrayTest<T>(
data: T
): T | undefined {
if(Array.isArray(data)){
// return 1 // error here if try to return number when data is an array
return data
}
else{
return Math.random() > 0.5 ? data : undefined
}
}
const arr = arrayTest(['a'])
const str = arrayTest('a')
const num = arrayTest(1) // error here because of passing in number
但在你的情况下,你也可以使用静态返回类型,虽然不如函数重载安全
function arrayTest<T extends string | string[]>(
data: T
): T | undefined {
if(Array.isArray(data)){
return data
}
else{
return Math.random() > 0.5 ? data : undefined
}
}
const arr = arrayTest(['a'])
const str = arrayTest('a')
const num = arrayTest(1) // error