【发布时间】:2021-08-10 18:39:28
【问题描述】:
我试图用纯 Javascript 编写的是:
const cleanVar = (var1): T => var1?.replace(searchValue, replaceValue);
在 Typescript 中,我希望能够将其输入为:
const cleanVar = <T extends string | undefined>(var1: T): T => var1?.replace(searchValue, replaceValue);
但我收到此错误:
Type 'string | undefined' is not assignable to type 'T'.
'string | undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
Type 'undefined' is not assignable to type 'T'.
'undefined' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | undefined'.
那么,输入这个函数的正确方法是什么?
含义应该是:var 可以是string 或undefined。如果var 是string,则返回类型必须是string。如果var 是undefined,则返回类型必须是undefined。
【问题讨论】:
-
问题是你的返回类型不是
string,而是T,它扩展了string。T可以是任何东西,但String.prototype.replace总是返回string,而不是T,所以打字稿不能保证cleanVar的返回类型是T,因为它知道它是@ 987654343@. -
顺便说一句,我认为 TypeScript 根本无法推断出
String.prototype.replace确实在 Javascript 中返回了T。请参阅此证明:typescriptlang.org/play?jsx=0#code/… -
你当然是对的。
extends有替代品吗?我可以用它来将T限制为string和undefined?
标签: typescript generics typescript-typings typescript-generics