Ant*_*deo 5 type-inference typescript
我将今天遇到的问题简化为这个最小的示例。(游乐场链接)
function test() {
interface Foo<T> {
type: 'Bar'
}
function nextFoo<T>(it: Foo<T>): Foo<T> {
return it
}
let foo: Foo<string> | undefined = { type: 'Bar' }
while (foo !== undefined) {
// Type inference error here but TS has the correct inference when hovering over nextFoo
const next = nextFoo(foo)
foo = next // commenting this out masks the issue
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎是 TypeScript 应该能够处理的事情。当我将鼠标悬停nextFoo在 vscode 中时,它看起来确实正确地推断出那里的类型。设置foo为nextwhile 它可能会undefined导致这种情况。
有人可以解释一下这是怎么回事吗?
小智 1
作为解决方法,您可以强类型化next变量:
function test() {
interface Foo<T> {
type: 'Bar'
}
function nextFoo<T>(it: Foo<T>): Foo<T> {
return it
}
let foo: Foo<string> | undefined = { type: 'Bar' }
while (foo !== undefined) {
// Type inference error here but TS has the correct inference when hovering over nextFoo
const next: Foo<string> | undefined = nextFoo(foo)
foo = next // commenting this out masks the issue
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4103 次 |
| 最近记录: |