【发布时间】:2019-06-07 15:27:38
【问题描述】:
如果您在下面的the typescript playground 上尝试我的 sn-p,它会在第 24 行显示错误。
我意识到可以通过再次将命令显式转换为 <IPlan[]> 来修复它,但为什么有必要这样做?
Property 'commands' in type 'Thing' is not assignable to the same property in base type 'AbstractThing'.
Type '{ plan: number; }[]' is not assignable to type 'IPlan[]'.
Type '{ plan: number; }' is not assignable to type 'IPlan'.
Types of property 'plan' are incompatible.
Type 'number' is not assignable to type '0 | 10 | 20'.
(property) Thing.commands: { plan: number; }[]
这是sn-p:
interface IPlan {
plan: 0 | 10 | 20;
}
// fine
let obj: IPlan = {
plan: 0
};
// also fine
let commands: IPlan[] = [
{
plan: 10
}
];
// not fine
abstract class AbstractThing {
commands?: IPlan[];
}
class Thing extends AbstractThing {
// this line has the error
commands = [
{
plan: 10
}
]
}
【问题讨论】:
-
plan: 10 as 10会工作的! -
在
Thing中分配变量的方式有些奇怪,因为您是从方法中分配它的。您应该尝试将赋值放在构造函数中,它会修复错误 -
这是一个known issue...他们tried and failed 之前修复了这个multiple times;目前,
extends类的成员没有上下文类型。对此的好评是here。 -
@jcalz 您的评论是对为什么它不起作用的最正确解释。如果你能把它作为答案,我很乐意接受它作为解决方案
标签: javascript typescript