typescript 在打字稿中使用类型作为值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41833150/
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
Using a type as a value in typescript
提问by Jonathan Rupp
I'm using inject-loader
to mock dependencies for a Typescript project being unit tested. The service I'm testing has an import line like this:
我正在使用inject-loader
模拟正在单元测试的 Typescript 项目的依赖项。我正在测试的服务有一个像这样的导入行:
import pnp, { SearchQuery, Sort, SortDirection, CamlQuery } from "sp-pnp-js";
For my test, I want to mock several of the functions on pnp, but keep the classes intact. In my unit test file, I've included this import:
对于我的测试,我想模拟 pnp 上的几个函数,但保持类完整。在我的单元测试文件中,我包含了这个导入:
import { SearchQuery, Sort, SortDirection, CamlQuery } from "sp-pnp-js";
Which gives my test access to the necessary classes. I've declared a mock service object:
这使我的测试可以访问必要的类。我已经声明了一个模拟服务对象:
// mock services
const mockPnp = {
default: { ... }
};
Which I'm wiring into my target class instance:
我正在连接到我的目标类实例:
Service = require("inject!./sharepointservice")({
"sp-pnp-js": mockPnp
}).Service;
And everything works, so long as I don't run any code that references those classes (ie. SearchQuery
). To get that to work, I tried adding it to the mock:
一切正常,只要我不运行任何引用这些类的代码(即。SearchQuery
)。为了让它起作用,我尝试将它添加到模拟中:
// mock services
const mockPnp = {
default: { ... },
SearchQuery: SearchQuery
};
However, I get a 'SearchQuery' only refers to a type, but is being used as a value here
error.
但是,我收到一个'SearchQuery' only refers to a type, but is being used as a value here
错误。
I've tried casting to any
(same error), tricks with modules and exports, with no luck. I'm supposed to be able to write any Javascript with Typescript, and this would work trivially in Javascript - what am I missing here?
我试过转换到any
(相同的错误),使用模块和导出的技巧,但没有运气。我应该能够用 Typescript 编写任何 Javascript,这在 Javascript 中可以正常工作 - 我在这里缺少什么?
采纳答案by Nitzan Tomer
According to the definition fileSearchQuery
is an interface, which means that you can not treat it as a value (as the error message says).
根据定义文件SearchQuery
是一个接口,这意味着您不能将其视为值(如错误消息所述)。
Typescript interfaces aren't being compiled into the js output, and you can not use them at runtime.
Typescript 接口不会被编译到 js 输出中,并且您不能在运行时使用它们。
回答by bresleveloper
Technically, since its just for type safety, I can do this
t: MyInterface = {};
从技术上讲,因为它只是为了类型安全,我可以这样做
t: MyInterface = {};