【发布时间】:2023-03-21 07:34:01
【问题描述】:
我最近升级到 typescript 2.4,我收到了几个错误,抱怨我的类型不再可分配。
这是我遇到错误的场景:
interface Parent {
prop: any
}
interface Child extends Parent {
childProp: any
}
type Foo<T> = <P extends Parent>(parent: P) => T
function createFooFunction<T>(arg: T): Foo<T> {
// Error here!
return (child: Child): T => {
return arg;
}
}
在 typescript 2.3 中这是可以接受的,但是 typescript 2.4 会产生这个错误
Type '(child: Child) => T' is not assignable to type 'Foo<T>'.
Types of parameters 'child' and 'parent' are incompatible.
Type 'P' is not assignable to type 'Child'.
Type 'Parent' is not assignable to type 'Child'.
Property 'childProp' is missing in type 'Parent'.
关于错误的最后一行,我注意到如果我将 Child 的属性设为可选,那么 typescript 将得到满足,即如果我进行此更改
interface Child extends Parent {
childProp?: any
}
虽然这不是一个理想的解决方案,因为在我的情况下, childProp 是必需的。
我还注意到将 Foo 的参数类型直接更改为 Parent 也将满足 typescript,即进行此更改
type Foo<T> = (parent: Parent) => T
这也不是一个修复,因为我不控制 Foo 类型,也不控制 Parent。它们都来自供应商 .d 文件,所以我无法修改它们。
但无论哪种方式,我都不确定我是否理解为什么这是一个错误。 Foo 类型是说它需要扩展 Parent 的东西,而 Child 就是这样一个对象,那为什么 typescript 会认为它不可赋值呢?
编辑:我已将此标记为已回答,因为添加 --noStrictGenericChecks 标志将抑制错误 (accepted answer here)。但是,我仍然想知道为什么首先这是一个错误,因为我宁愿严格检查并在错误时重构我的代码,而不是仅仅将其短路。
所以要重申问题的核心,既然 Child 扩展了 Parent,为什么打字稿不再认为 Child 可以分配给 Parent,并且就 OOP 泛型而言,为什么这比以前更正确?
【问题讨论】:
标签: typescript generics typescript2.0 typescript2.4