Typescript 中的匿名类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20073520/
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
Anonymous class in Typescript
提问by ic3
Getting some trouble to do the following in typescript. I've the following interface defined :
在打字稿中执行以下操作时遇到一些麻烦。我定义了以下接口:
interface RendererCallback {
getNode():HTMLElement;
getTable();
}
There is a method expecting a RenderCallback object like :
有一种方法需要 RenderCallback 对象,例如:
render( callback:RendererCallback )
How do I create an anonymous instance in the middle of my code :
如何在我的代码中间创建一个匿名实例:
myObject.render( new .. {
getNode() {
return myNode;
}
getTable() {
.. some code...
return something;
}
} );
回答by MgSam
You can use anonymous objects and lambdas:
您可以使用匿名对象和 lambdas:
myObject.render({
getNode: () => { doSomething...; return myNode },
getTable: () => myTable
});
Note, the new
keyword is not used.
请注意,new
未使用关键字。
回答by stuffins
Typescript now supports class expressions so you can make actual anonymous classes.
Typescript 现在支持类表达式,因此您可以创建实际的匿名类。
myObject.render( new class {
getNode() {
return myNode;
}
getTable() {
.. some code...
return something;
}
} );
This has the benefit of this
not being inferred to be any
within the anonymous class' methods.
这样做的好处是this
不会被推断为any
在匿名类的方法中。
回答by Alex Dresko
Here's a full code sample that works:
这是一个有效的完整代码示例:
interface RendererCallback {
getNode():HTMLElement;
getTable();
}
class thing {
render(callback: RendererCallback) {
}
}
var myObject = new thing();
myObject.render( {
getNode() {
return null;
},
getTable() {
}
}
);
回答by joeystdio
I find it to nice to declare it like this:
我发现像这样声明它很好:
propertyName: RendererCallback = {
getNode: () => myNode, // no braces needed to only return something
getTable() => {
.. some code...
return something;
}
};