typescript TS2339:类型 {} 上不存在属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34179728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TS2339: Property does not exist on type {}
提问by Richard
Please help me fix this compilation error.
请帮我修复这个编译错误。
Below you can see the compiler complaining that the Actionsobject on line 20 (I removed a few lines for clarity before posting this) is {}:
在下面,您可以看到编译器抱怨第 20 行的Actions对象(为了清楚起见,我在发布之前删除了几行)是 {}:
But below you can see in actions.tsthat Actionsis an object of type Actions, and it has the requested property (which is a function):
但是,下面你可以看到在actions.ts该操作是类型的对象操作,并具有所要求的特性(这是一个功能):
And in the base code you can see in the DefinitelyTyped Altdefinition that createActionsshould return an object of type Actions:
在基本代码中,您可以在绝对类型的Alt定义中看到createActions应返回类型为Actions的对象:
So why is Typescript complaining that Actions is not of type Actions?
那么为什么 Typescript 会抱怨 Actions 不是 Actions 类型呢?
回答by mk.
You're using a module called "app/actions/actions"
. That module is actually not a module (a map of properties), but whatever's the result of flux.createACtions(Actions)
:
您正在使用一个名为"app/actions/actions"
. 该模块实际上不是模块(属性映射),但无论结果如何flux.createACtions(Actions)
:
export = flux.createActions(Actions); // in actions.ts
What does that return? Because you're not specifying the generic for <T>
, and because the params of createActions
don't correctly include a T
from which it could infer, it assumes that T
is just {}
. This was discussed hereand ultimately declined. So, as mentioned, you need to specify the generic:
那返回什么?因为您没有指定 for 的泛型<T>
,并且因为 的 paramscreateActions
没有正确包含T
它可以推断的 a,所以它假设它T
只是{}
. 这在这里被讨论过,最终被拒绝了。因此,如前所述,您需要指定泛型:
export = flux.createActions<Actions>(Actions);
But to avoid this, you could change your local (or remote) alt.d.ts
to be something like:
但是为了避免这种情况,您可以将本地(或远程)alt.d.ts
更改为:
class Alt {
createActions<T extends ActionsClass>(con: ActionsClassConstructor<T>, ...): T;
}
type ActionsClassConstructor<T extends ActionsClass> = new (alt:Alt) => T;
This adds the generic type info needed to correctly infer based on the constructor you supply.
这添加了根据您提供的构造函数正确推断所需的通用类型信息。