【发布时间】:2021-05-26 12:12:40
【问题描述】:
所以我可以重载函数:
function myFunc(x : number) : number
function myFunc(x : string) : string
function myFunc(x : number | string) : number | string {
if (typeof x == "string") {
return x + "1"
} else {
return x + 1
}
}
它有效:
const x = myFunc(1) // correctly inferred as number
const y = myFunc("1") // correctly inferred as string
此语法不会防止重载实现中的混合类型:
function myFunc(x : number) : number
function myFunc(x : string) : string
function myFunc(x : number | string) : number | string {
if (typeof x == "string") {
return 1 // !!! no type error
} else {
return "1" // !!! no type error
}
}
如果我添加泛型,即使是“正确”版本也会出现错误:
function myFunc(x : number) : number
function myFunc(x : string) : string
function myFunc<T extends number | string>(x : T) : T {
if (typeof x == "string") {
return "1" // !!! ERROR
} else {
return 1 // !!! ERROR
}
}
我得到了很好的旧:
TS2322: Type 'number' is not assignable to type 'T'. 'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.
两个分支。基本上和刚刚的一样
function myFunc<T extends number | string>(x : T) : T {
if (typeof x == "string") {
return "1" // !!! could be instantiated with a different subtype... ERROR
} else {
return 1 // !!! could be instantiated with a different subtype... ERROR
}
}
有没有办法限制重载函数中的输入输出类型,使其不具有上述限制?这看起来很常见,但不知何故我在 Google 中找不到答案。
【问题讨论】:
-
return x + 1 // !!! no type error- 即使没有联合类型打字稿也允许这个typescriptlang.org/play?#code/… -
@Ivan Kleshnin 不要忘记 TS 只是 JS 的扩展。
+允许对字符串进行操作 -
谢谢。我更新了描述以关注主要问题(不归结为操作员)。
-
通用版本的问题在于,从打字稿的角度来看,它可以称为
myFunc<'foo'>('foo'),例如
标签: typescript