[英]Abstract interface cannot be used as type in array - missing property
我有這個界面:
export interface SceEvent {
// ...
}
export interface SceMain {
onComplete: () => void;
onNextEvent: (ev: SceEvent) => void;
getRawGeneratedCode: () => string;
getStyledGeneratedCode: () => string;
}
我在幾個看起來像這樣的文件中實現了此接口:
import {SceEvent, SceMain} from "../../interfaces";
export class CodeGenerator implements SceMain {
private rawCode = '';
private styledCode = '';
public static pluginName = 'java-junit';
constructor(){
}
getRawGeneratedCode() {
return this.rawCode;
}
getStyledGeneratedCode() {
return this.styledCode;
}
onComplete(){
}
onNextEvent(ev: SceEvent) {
}
}
然后在另一個文件中,導出所有這些實現:
import {SceMain} from "./interfaces";
// generators
import * as javajunit from './values/java-junit';
import * as javatestng from './values/java-test-ng';
import * as nodejsmocha from './values/nodejs-mocha';
import * as nodejssuman from './values/nodejs-suman';
export const plugins : Array<SceMain>= [
javajunit.CodeGenerator,
javatestng.CodeGenerator,
nodejsmocha.CodeGenerator,
nodejssuman.CodeGenerator
];
但我收到此錯誤:
typeof CodeGenerator中缺少屬性“ onComplete”
我不明白,因為我所有的CodeGenerator類都實現了此方法。
這是圖像上的錯誤...
有人知道這里可能會發生什么嗎?
因為插件是構造函數的數組,而不是實例的數組,所以類型需要更改:
// 原版的
plugins: Array<SceMain>
//改進
plugins: Array<new() => SceMain>
感謝@jcalz的答案
plugins
常量是SceMain
構造函數的數組,而不是SceMain
實例的數組。 SceMain
的實例具有類似onComplete()
方法,但構造函數則沒有(除非它碰巧具有帶有正確簽名的靜態方法)。 編譯器警告您數組的元素不是SceMain
實例。
假設您實際上打算創建一個構造函數數組(如您的評論中所述),則應鍵入如下plugins
:
export const plugins : Array<new() => SceMain>= [
javajunit.CodeGenerator,
javatestng.CodeGenerator,
nodejsmocha.CodeGenerator,
nodejssuman.CodeGenerator
];
類型new() => SceMain
是生成SceMain
實例的無參數構造函數的類型。 (如果構造函數接受參數,則應修改類型。)
您可能會因為以下事實而感到困惑:在TypeScript中,當您聲明一個名為class
class Foo {}
,它會創建一個名為Foo
的類型 (對應於該類的實例)和一個名為Foo
的值 ,該值是Foo
的構造函數。類。 值Foo
不是Foo
類型。 但是,它的類型為new ()=>Foo
。 您可以使用typeof
類型運算符來獲得類構造函數的更特定類型(包括靜態方法): typeof Foo
是Foo
構造函數的類型。 您可以在《 TypeScript手冊》中了解更多信息。
類型表達式和值表達式之間的區別很難解釋,特別是因為TypeScript傾向於在兩種類型的表達式中使用相同的關鍵字來表示不同的(並且可能只是邊緣相關):
class Foo {}
const foo: Foo = new Foo();
// the first Foo is the instance type,
// the second Foo is the constructor value
const fooConstructor: typeof Foo = Foo;
// the first Foo is the constructor value
// typeof is a type query acting on it at design time
// the second Foo is the constructor value
const theWordFunction: string = typeof Foo;
// Foo is the constructor value
// typeof is the JavaScript typeof operator acting on it at runtime
// It will just be "function"
我不知道這是否使事情變得更糟或更糟。 無論如何,祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.