在 Typescript 中,我們有辦法從陣列中訪問型別,如下所示。
const list = [item,item2] as const;
type typeOfArray = typeof list[number];
const something: typeOfArray = ; // item | item2
我試圖通過類來獲得它,但得到“型別錯誤中缺少屬性'原型'”
如果我將類宣告為型別,它可以正常作業,但無法通過typeof. 這是 Typescript 的缺點嗎?如果您有解決方案,將感謝您的幫助。
請使用以下代碼作為示例設定:
class A {
methodA() {
}
}
class B {
methodB() {
}
}
class C {
methodC() {
}
}
const classList = [A,B,C] as const;
這作業得很好:
type classSelection = A | B | C;
let o: classSelection;
o = new A();
o. // o.methodA;
這給出了上述錯誤:
type classSelection = typeof classList[number];
o = new A(); //Type 'A' is not assignable to type 'typeof A | typeof B | typeof C'.
Property 'prototype' is missing in type 'A' but required in type 'typeof C'
uj5u.com熱心網友回復:
您的classList變數是一個類建構式陣列:
const classList = [A, B, C] as const;
// const classList: readonly [typeof A, typeof B, typeof C]
這意味著當您使用鍵型別對其型別進行索引時number,您將獲得這些建構式型別的聯合:
type ClassConstructors = typeof classList[number];
// type ClassConstructors = typeof A | typeof B | typeof C
類建構式本身不是實體;相反,它們具有看起來像的構造簽名{new (): A}(這意味著在其上使用不帶引數的new運算子將產生 type 的值A)。
有一個InstanceType<T>實用程式型別,它采用具有構造簽名的型別并回傳相應的實體型別。如果將其應用于建構式型別的聯合,則會得到實體型別的聯合:
type ClassSelection = InstanceType<typeof classList[number]>;
// type ClassSelection = A | B | C
然后你的其余代碼應該可以作業:
let o: ClassSelection = new A(); // okay
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405754.html
標籤:
上一篇:MOBX和React集成
下一篇:打字稿通用,如何?
