【发布时间】:2021-08-26 17:08:01
【问题描述】:
我创建了以下示例代码以最小化重现我的问题:
class Test {
prop1 : boolean
prop2 : string
method() { }
static create(prop1 : boolean, prop2 : string) : Test {
let item : Test = {
prop1: prop1,
prop2: prop2
}
return item;
}
}
请注意,在我的实际代码中,与 create 等效的是一个工厂方法,它可能会返回子类的实例(这就是为什么我选择将其设为静态方法而不是构造函数的原因)。
不幸的是,对于这段代码,我得到以下编译错误:
错误 TS2741:类型“{ prop1: boolean; ”中缺少属性“方法”道具2:字符串; }' 但在“测试”类型中是必需的。
当我在 Visual Studio Code 中将鼠标悬停在 method 上时,Intellisense 正确地将其列为方法,不是属性。但是,错误消息(错误地)指出它是一个属性。
我尝试阅读以下问答,但它们没有帮助我:
error TS2741: Property is missing in type - 接受的答案是关于方法接受的参数类型,但我的 MRE 中的方法不接受参数
How to fix "Property 'type' is missing in type but required in type 'SeriesXrangeOptions'" in angular highcharts module - 解决方案似乎与我的问题无关
Typescript / Angular 2: Property is missing in type - 那是由于不正确地实现接口引起的,但我没有实现接口
谁能解释我为什么会收到这个错误以及如何解决它?
【问题讨论】:
-
你需要使用
new来创建类的实例。
标签: angular typescript angular8