[英]Why does TypeScript complain about my implementation of an abstract class member?
Below is my custom type: 以下是我的自定义类型:
type KeyMap<T> = { [K in keyof T]: keyof Pick<T, K> }
Followed by a simple interface to use with the custom type: 后跟一个用于自定义类型的简单界面:
interface MyInterface {
a: string;
b: string;
}
When variable of my type is defined outside of a class, TypeScript is happy: 当我的类型的变量在类之外定义时,TypeScript很高兴:
const member: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
}
But when I define an abstract class with an abstract member of type KeyMap
and try to implement it, it does not work. 但是,当我使用
KeyMap
类型的抽象成员定义一个抽象类并尝试实现它时,它将无法工作。 For example: 例如:
abstract class BaseClass<T> {
protected abstract member: KeyMap<T>
protected abstract method: () => void;
}
class DerivedClass extends BaseClass<MyInterface> {
// TypeScript reports that property 'a' is not compatible with '"a"'
protected member = {
a: 'a',
b: 'b'
};
protected method = () => console.log('');
}
Defining member directly in the abstract or derived class seems to work. 直接在抽象或派生类中定义成员似乎可行。 For example:
例如:
abstract class BaseClass {
public member: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
}
protected abstract method: () => void;
}
class DerivedClass extends BaseClass {
public derivedMember: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
}
protected method = () => console.log('');
}
As does changing member to be a different type: 就像将成员更改为其他类型一样:
abstract class BaseClass<T> {
protected abstract member: { c: string, d: string };
protected abstract method: () => void;
}
class DerivedClass extends BaseClass<MyInterface> {
protected member = {
c: 'c',
d: 'd'
};
protected method = () => console.log('');
}
Why does TypeScript report the implementation of member
in the derived class as an error when it works outside of the class and when it's not marked as abstract? 当TypeScript在类之外工作且未标记为抽象时,为什么将派生类中
member
的实现报告为错误?
Class members are types without regard to what is in the base class, and only then is the derived class checked for compatibility with the base class. 类成员是类型,而不考虑基类中的内容,只有这样才检查派生类与基类的兼容性。 Since the member is typed based on the initialization value, typescript will not use literal types for property types (there are only certain places TS will not widen a literal type and this is not one of them)
由于成员是根据初始化值键入的,因此typescript不会将文字类型用于属性类型(只有某些地方TS不会扩展文字类型,这也不是其中之一)
The best think you can do is use an explicit type annotation for the member as you already say you tried in your question: 您可以做的最好的想法就是为成员使用一个显式类型注释,就像您已经说过在问题中尝试过的那样:
class DerivedClass extends BaseClass<MyInterface> {
protected member: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
};
protected method = () => console.log('');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.