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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:09:24  来源:igfitidea点击:

TS2339: Property does not exist on type {}

typescriptfluxalt.js

提问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 {}: enter image description here

在下面,您可以看到编译器抱怨第 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): enter image description here

但是,下面你可以看到在actions.ts操作是类型的对象操作,并具有所要求的特性(这是一个功能): 在此处输入图片说明

And in the base code you can see in the DefinitelyTyped Altdefinition that createActionsshould return an object of type Actions: enter image description here

在基本代码中,您可以在绝对类型的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 createActionsdon't correctly include a Tfrom which it could infer, it assumes that Tis 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.tsto 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.

这添加了根据您提供的构造函数正确推断所需的通用类型信息。