Typescript typeof sınıf ve türetilmiş sınıflar


Bir temel sınıfım var ve bu sınıf birkaç alt sınıf tarafından genişletiliyor. Şimdi bir özelliğin türü olarak ana sınıfın türüne sahip olmak istiyorum. Tüm alt türler de geçerli olmalı. typeof denedim ama bu işe yaramıyor. Bir özelliğin türü olarak bir temel sınıfın türüne sahip olmanın bir yolu var mı? Türe bir referans sahibi olmak istememin nedeni, yeni sınıf örnekleri oluşturabilmek; örneğin new test.componentType() ifadesi Child2'nin yeni bir örneğini oluşturmalı.

class Parent {

}

class Child1 extends Parent {

}

class Child2 extends Parent {

}

interface Config {
    componentType: typeof Parent;
}

const test: Config = {
    componentType: typeof Child2
}

new test.componentType() -> should create a new instance of Child2

Cevap #1

Kodunuz çalışmıyordu çünkü Child2 zaten sınıf nesnesiydi ve bu typeof Parent ile uyumluydu. test şu şekilde tanımlanmalıydı:

const test: Config = {
    componentType: Child2
}

Yine de, sadece componentType alanının bir yapıcıyı tutmasını istiyor gibisin. Bu durumda, componentType öğesini new yöntemi ile bir nesne olarak prototip oluşturabilirsin:

interface Config {
    componentType: { new(): Parent };
}

const test: Config = {
    componentType: Child2
}

const myinstance: Parent = new test.componentType();

Oluşturulan örnek türleri hakkında bilgi tutmak için, genel bir tür kullanılabilir:

interface Config<T extends Parent> {
    componentType: { new(): T };
}

const test = {
    componentType: Child2
}

const myinstance: Child2 = new test.componentType();

İlgili makaleler