問題
我有以下設定(游樂場鏈接):
class Foo<T> {
constructor(x: T) {
console.log(x);
}
}
class Bar extends Foo<string> {
}
現在我想創建一個函式,它接受Foo.
實體作業正常:
function takesFoo(x: Foo<any>) {
// ...
}
takesFoo(new Bar("hi"));
但是,如果我想使用建構式,它會失敗:
function takesFooConstructor(x : typeof Foo) {
// ...
}
takesFooConstructor(Bar);
// ^^^------ Argument of type 'typeof Bar' is not
// assignable to parameter of type 'typeof Foo'.
為什么這不起作用,我該如何解決?
我已經嘗試過的一些事情
// Maybe I should make the function a generic?
function takesFooCtorGeneric<T extends typeof Foo>(x: T) {
// ...
}
takesFooCtorGeneric(Bar);
// ^^^----- nope
// This works, but I don't want to cast every time I call the function.
takesFooConstructor(Bar as typeof Foo);
function parametersOnly<T extends Foo<any>>(x: (...args: any) => T) {
// ...
}
parametersOnly(Bar)
// ^^^------ Type 'typeof Bar' provides no match for the
// signature '(...args: any): Foo<any>'.
// This works, but now I can't access static properties.
type Constructor = Function & { prototype: Foo<any> }
function usePrototype(ctor: Constructor) {
console.log(ctor.someStaticProp);
// ^^^^^^^^^^^^^^------ Property 'someStaticProp' does
// not exist on type 'Constructor'
}
usePrototype(Bar);
uj5u.com熱心網友回復:
TypeScript中類的建構式具有以下簽名:new和呼叫簽名。在您的情況下,建構式的Bar型別為new (x: string) => Bar。
如果你想takesFooConstructor采取Foo建構式:
function takesFooAndExtendersOfFooConstructorWitoutDefinedT(x : new <T>(x: T) => Foo<T>)
但是在那種情況下takesFooConstructor不能采用 Bar 建構式,因為您已經定義T了Foo.
如果你想takesFooConstructor獲取Foo任何擴展類的建構式和建構式Foo:
function takesAnyConstructorsOfFooAndExtendersOfFoo<T>(x : new (x: T) => Foo<T>)
兩種方法的游樂場
uj5u.com熱心網友回復:
問題Foo是通用的。這意味著takesFooConstructor將期望收到一個通用類,它可以作業Ex。這是因為 takeFooConstructor 可以將作為引數傳入的類實體化為 any T,但Bar只接受string.
您可以改用建構式簽名,但您必須重寫建構式引數:
function takesFooConstructor<T>(x : new (x: T) => Foo<T>) {
}
takesFooConstructor(Bar);
takesFooConstructor(Foo);
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390802.html
標籤:打字稿
上一篇:TypeScript陣列差異
