typescript 不能在表达式打字稿中使用 new
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41017287/
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
Cannot use new with expression typescript
提问by VJAI
interface Window {
AudioContext: AudioContext;
webkitAudioContext: Function
}
let contextClass = window.AudioContext || window.webkitAudioContext;
let context: AudioContext = new contextClass();
The last line is giving me this error,
最后一行给了我这个错误,
Cannot use 'new' with an expression whose type lacks a call or construct signature
不能对类型缺少调用或构造签名的表达式使用“new”
How can I resolve this?
我该如何解决这个问题?
回答by haim770
The problem is that the compiler treats the contextClass
variable as an instanceof AudioContext
while in fact it's merely a constructor function for an AudioContext
.
问题在于编译器将contextClass
变量视为 的实例,AudioContext
而实际上它只是AudioContext
.
You can simply use any
and the compiler will let you new
it:
你可以简单地使用any
,编译器会让你new
:
let contextClass : any = window.AudioContext || window.webkitAudioContext;
let context: AudioContext = new contextClass();
Another option would be to introduce a Constructable<T>
interface that will let you new
up those types:
另一种选择是引入一个Constructable<T>
接口,让您new
可以使用这些类型:
interface Constructable<T> {
new(...args: any) : T;
}
interface Window
{
AudioContext: Constructable<AudioContext>;
webkitAudioContext: Constructable<AudioContext>
}
let contextClass = window.AudioContext || window.webkitAudioContext;
let context: AudioContext = new contextClass();
回答by Nathan Cooper
You can't new up an instance. new instanceofAudioContext()
isn't a valid thing to do.
你不能新建一个实例。new instanceofAudioContext()
不是一件有效的事情。
Your interface doesn't match the API you're trying to use. In the browser, window.AudioContext
isn't a instance of AudioContext
. It's the class definition method, typeof AudioContext
. You'll also have the same problem with the Function
.
您的界面与您尝试使用的 API 不匹配。在浏览器中,window.AudioContext
不是AudioContext
. 它是类定义方法,typeof AudioContext
. 你也会遇到同样的问题Function
。
If you'd still like to keep your interface. Try this
如果您仍然想保留您的界面。尝试这个
interface Window {
AudioContext: typeof AudioContext;
webkitAudioContext: typeof AudioContext
}
declare var window: Window;
var AudioContextDecl = window.AudioContext || window.webkitAudioContext;
var audioCtx = new AudioContext();
Or if you don't want the interface,
或者如果你不想要界面,
var AudioContextDecl = <typeof AudioContext>(window.AudioContext || window.webkitAudioContext);
var audioCtx = new AudioContext();
Or even just use any
. It all transpiles to the same thing.
或者甚至只是使用any
. 这一切都转化为同一件事。