![](/img/trans.png)
[英]Typescript: Argument of type X is not assignable to parameter of type Y & X. Type X is not assignable to type Y
[英]TYPESCRIPT : Argument of type 'typeof X' is not assignable to parameter of type 'Y' with extends
我开始用打字稿编码,但我有一些编译问题。
我有几个班级,似乎我有层次结构问题
在我的第一堂课 (A) 上,我指出了一组属性/功能。 我有第二个类 (B),它继承自类 (A) 并添加了某些属性/功能。 最后,我有一个继承自第二个类 (B) 的第三个类 (C)。
export default class A {
prop1: string;
function1() {
console.log('TEST');
}
}
export default class B extends A {
prop2: string;
function2() {
console.log('TEST');
}
}
export default class C extends B {
prop3: string;
function3() {
console.log('TEST');
}
}
编译时,我收到以下错误消息:
TS2345:“typeof C”类型的参数不可分配给“A”类型的参数。 类型“typeof C”缺少类型“B”中的以下属性:prop1、function1。
我的 3 个类在 3 个单独的文件中,我使用导出/导入,它似乎工作......
你有想法吗?
TSCONFING:
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
我正在尝试制作类似此链接的代码。 网站上的错误消息听起来与我在编辑器中的不太一样,但也许在网站上更正时我会发现最终问题......
非常感谢。
感谢游乐场链接,它有助于找到问题。
它不起作用,因为你想存储一个工厂,要求一个实例。
主要技巧在这里:
registeredTypes: Map<string,typeof ComponentBase>
完整的固定版本在这里:
export class ComponentBase {
prop: string;
constructor(prop: string) {
this.prop = prop;
}
}
export class Component extends ComponentBase {
otherProp: string;
constructor(prop: string, otherProp: string) {
super(prop);
this.otherProp = otherProp;
}
}
export class ButtonGeneric extends Component {
buttonProp: string;
constructor(buttonProp: string) {
super('prop', 'otherProp');
this.buttonProp = buttonProp;
}
}
export class ButtonSpecific extends ButtonGeneric {
buttonSpecProp: string;
constructor(buttonSpecProp: string) {
super('buttonProp')
this.buttonSpecProp = buttonSpecProp;
}
}
export class ComponentFactory {
registeredTypes: Map<string,typeof ComponentBase>
constructor() {
this.registeredTypes = new Map<string,typeof ComponentBase>();
}
register(className: string, classConstructor: typeof ComponentBase) {
if (!this.registeredTypes.has(className)) {
this.registeredTypes.set(className, classConstructor);
}
}
create(className: string, properties: string) {
if (!this.registeredTypes.has(className)) {
throw Error('The class [' + className + '] doesn\'t exists. Couldn\'t create new object');
}
let classConstructor = this.registeredTypes.get(className);
if (classConstructor == null) { throw new Error('') }
const instance = new classConstructor(properties);
return instance;
}
}
const FactoryButtonConst = 'button';
export class ButtonFactory extends ComponentFactory {
constructor() {
super();
this.register(FactoryButtonConst, ButtonSpecific);
}
createButtonSpecific(buttonSpecProp: string) {
return this.create(FactoryButtonConst, buttonSpecProp);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.