【发布时间】:2021-05-04 05:59:20
【问题描述】:
我正在寻找关于联合类型缩小的具体行为。我有以下联合类型的“可订购”类型:
type Orderable = string | number
我使用这种类型作为函数类型参数的约束,如下:
function foo<T extends Orderable>(x: T, y: T): void {
// ...
}
// x and y must be of the same type within T,
// and this constraint works from the usage perspective:
foo('bar', 'baz') // OK
foo(21, 42) // OK
foo('bar', 42) // ERROR
我不确定我想要的是否在 Typescript 中完全可行,但我希望能够在应用于 T 实例的函数中使用类型缩小,而不是在变量 (@987654324 @ 和 y),其类型被限制为 T。为了向您展示我的意思,我希望能够做到以下几点:
function foo<T extends string | number>(x: T, y: T): void {
if (typeof x === 'string') {
// if x = string, then T = string,
// thus y = string, and can be assigned to z:
const z: string = y
}
}
但上面对z 的赋值给出了错误
Type 'T' is not assignable to type 'string'.
- Type 'string | number' is not assignable to type 'string'.
- - Type 'number' is not assignable to type 'string'.
换句话说,if 语句应该“证明”T = string,但它只证明了x extends string。尽管证明x 是一个字符串并不能证明y 的类型确实让有些 有意义,但考虑到foo('bar', 42) 抛出错误的使用示例,我仍然认为这很奇怪;导致该错误的类型检查和函数体内的类型检查都依赖于 foo 的相同函数签名。如何正确解释这种(对我来说出乎意料的)行为?有没有其他方法可以进行这种缩小范围?
提前致谢!
【问题讨论】:
标签: typescript generics