如何创建一个接口来接收 class,而不是打字稿中 class 的实例
How can I create a interface that receives a class, and not a instance of the class in typescript
我想创建一个接收实际 class 而不是 class 实例的接口。
像这样:
class checkIfGonextPage{
localResult;
next;
constructor(localResult:string,next:string){
this.localResult=localResult;
this.next=next;
}
}
interface comp{
CheckifCanGoNext: checkIfGonextPage;
}
let x:comp ={"CheckifCanGoNext":checkIfGonextPage}
let f = new x["CheckifCanGoNext"]("sss","")
console.log(f.localResult);
如果我将 CheckifCanGoNext 设置为 any,它会起作用,但我会丢失类型。
您始终可以使用 typeof
type query operator 来获取特定命名值的类型。如果你想把名为 CheckIfGonextPage
的实际值,class 构造函数,放在 Comp
的 CheckifCanGoNext
属性 中,那么你可以引用那个类型作为 typeof CheckIfGonextPage
:
interface Comp {
CheckifCanGoNext: typeof CheckIfGonextPage;
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }
let f = new x["CheckifCanGoNext"]("sss", "")
您也可以使用 construct signature to describe something that can be called with the new
operator. It looks like a function call signature,但在其前面加上单词 new
:
interface Comp {
CheckifCanGoNext: new (localResult: string, next: string) => CheckIfGonextPage
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }
let f = new x["CheckifCanGoNext"]("sss", "");
任何一种方法都应该有效。
我想创建一个接收实际 class 而不是 class 实例的接口。 像这样:
class checkIfGonextPage{
localResult;
next;
constructor(localResult:string,next:string){
this.localResult=localResult;
this.next=next;
}
}
interface comp{
CheckifCanGoNext: checkIfGonextPage;
}
let x:comp ={"CheckifCanGoNext":checkIfGonextPage}
let f = new x["CheckifCanGoNext"]("sss","")
console.log(f.localResult);
如果我将 CheckifCanGoNext 设置为 any,它会起作用,但我会丢失类型。
您始终可以使用 typeof
type query operator 来获取特定命名值的类型。如果你想把名为 CheckIfGonextPage
的实际值,class 构造函数,放在 Comp
的 CheckifCanGoNext
属性 中,那么你可以引用那个类型作为 typeof CheckIfGonextPage
:
interface Comp {
CheckifCanGoNext: typeof CheckIfGonextPage;
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }
let f = new x["CheckifCanGoNext"]("sss", "")
您也可以使用 construct signature to describe something that can be called with the new
operator. It looks like a function call signature,但在其前面加上单词 new
:
interface Comp {
CheckifCanGoNext: new (localResult: string, next: string) => CheckIfGonextPage
}
let x: Comp = { "CheckifCanGoNext": CheckIfGonextPage }
let f = new x["CheckifCanGoNext"]("sss", "");
任何一种方法都应该有效。