TypeScript:返回与参数相同的类型
TypeScript:返回与参数相同的类型,typescript,typescript-typings,typescript-generics,Typescript,Typescript Typings,Typescript Generics,formatISODate函数需要字符串值 如果没有定义,我需要转换许多字符串。 我可以这样做: { date1: date1 ? formatISODate(date1) : undefined, date2: date2 ? formatISODate(date2) : undefined ... } 为了避免重复相同的三元表达式,我编写了下面的函数 function convertDate<T extends string | undefined>(isoDate
formatISODate
函数需要字符串值
如果没有定义,我需要转换许多字符串。
我可以这样做:
{
date1: date1 ? formatISODate(date1) : undefined,
date2: date2 ? formatISODate(date2) : undefined
...
}
为了避免重复相同的三元表达式,我编写了下面的函数
function convertDate<T extends string | undefined>(isoDate?: string): T {
return isoDate ? formatISODate(isoDate) : undefined;
}
函数convertDate(isoDate?:字符串):T{
返回isoDate?formatISODate(isoDate):未定义;
}
但它有一个类型错误
错误:“undefined”可分配给“T”类型的约束,但“T”可以用约束“string | undefined”的不同子类型实例化
有可能解决这个用例的类型问题吗?让我们让这个例子更简单一些
function convertDate<T extends string | undefined>(isoDate?: string): T {
return undefined
}
然后根据您的签名,您希望返回类型为string。但在运行时情况并非如此!与函数中返回的子类型(未定义的
)不同,T可以用不同的子类型(此处为字符串
)实例化,这种差异用TypeScript错误表示
可能的解决方案:
说服编译器的唯一方法是强制转换返回类型:
declare function formatISODate(d: string): string
function convertDate<T extends string | undefined>(isoDate?: string): T {
return (isoDate ? formatISODate(isoDate) : undefined) as T
}
如果您的目标只是避免重复相同的三元表达式,那么可以使用上述代码实现。formatISODate是否有类型参数?如果不是的话,我不知道T给你买了什么。此函数应该只返回formatISODate的返回值| undefinedformatISODate没有类型,即它需要字符串并返回字符串。return
string | undefined
在使用date1:convertDate(date1)
时,如果date1完全是字符串,则会显示类型错误。我之前误读了。只需将其键入convertDate(isoDate?:string):string。假设您的tsconfig中没有启用严格的空检查(鉴于您的内联三元组似乎正在工作,我怀疑您是否启用了空检查),那么这应该是可行的。非常感谢您详细解释了它可能失败的原因。您是对的,泛型类型参数在这种情况下没有意义。
declare function formatISODate(d: string): string
function convertDate<T extends string | undefined>(isoDate?: string): T {
return (isoDate ? formatISODate(isoDate) : undefined) as T
}
function convertDate(isoDate?: string): string | undefined {
return isoDate ? formatISODate(isoDate) : undefined;
}