我在解决界面中定义构造函数的工作方式时遇到了一些麻烦.我可能完全误解了一些事情.但是我已经寻找了很长一段时间的答案,我找不到与此相关的任何内容.
如何在TypeScript类中实现以下接口:
interface MyInterface {
new ( ... ) : MyInterface;
}
Run Code Online (Sandbox Code Playgroud)
Anders Hejlsberg在此视频中创建了一个包含类似内容的界面(大约14分钟).但对于我的生活,我无法在课堂上实现这一点.
我可能误解了一些事情,我没有得到什么?
编辑:
澄清.用"new(...)"我的意思是"任何东西".我的问题是我无法得到这个工作的最基本版本:
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () { }
}
Run Code Online (Sandbox Code Playgroud)
这不是为我编译我得到"类'测试'声明接口'MyInterface'但没有实现它:类型'MyInterface'需要一个构造签名,但类型'test'在尝试编译它时缺少一个.
编辑:
因此,在研究了这一点后,给出了反馈意见.
interface MyInterface {
new () : MyInterface;
}
class test implements MyInterface {
constructor () => test { return this; }
}
Run Code Online (Sandbox Code Playgroud)
是无效的TypeScript,这不能解决问题.您无法定义构造函数的返回类型.它将返回"测试".下面的签名:class test {constructor(){}}似乎是"new()=> test"(通过将"代码"粘贴在在线编辑器中,将鼠标悬停在"class"上获得).这就是我们想要的和我认为的.
任何人都可以在实际编译时提供此类或类似的示例吗?
编辑(再次......):
所以我可能想出了为什么可以在接口中定义它但不能在TypeScript类中实现的想法.以下工作:
var MyClass = (function () {
function MyClass() { }
return …Run Code Online (Sandbox Code Playgroud) 就此而言,我对 TypeScript 甚至 JavaScript 还很陌生。我一直在尝试围绕 Microsoft 的一个示例,介绍如何将 AzureAD 身份验证集成到 React 应用程序中。该示例使用 HOC 为组件提供身份验证。HOC 的声明如下所示:
function withAuthProvider<T extends React.Component<AuthComponentProps>>(
WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}
Run Code Online (Sandbox Code Playgroud)
其中大部分或多或少是清楚的。令我困惑的是WrappedComponent. 具体来说,我不明白new关键字在该上下文中的作用。
谁能帮我吗?
我正在阅读类验证器库的代码,它具有以下isInstance方法:
/**
* Checks if the value is an instance of the specified object.
*/
isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any) {
return targetTypeConstructor
&& typeof targetTypeConstructor === "function"
&& object instanceof targetTypeConstructor;
}
Run Code Online (Sandbox Code Playgroud)
关于如何去理解类型有new (...args: any[]) => any什么想法吗?这是我第一次看到这种构造...
typescript ×3
javascript ×2
constructor ×1
instanceof ×1
interface ×1
reactjs ×1
validation ×1