为什么TypeScript抱怨我实现了一个抽象类成员?
以下是我的自定义类型:为什么TypeScript抱怨我实现了一个抽象类成员?,typescript,abstract-class,abstract,Typescript,Abstract Class,Abstract,以下是我的自定义类型: type KeyMap<T> = { [K in keyof T]: keyof Pick<T, K> } interface MyInterface { a: string; b: string; } 当my类型的变量在类之外定义时,TypeScript很高兴: const member: KeyMap<MyInterface> = { a: 'a', b: 'b' } 直接在抽象类或派生类中定义
type KeyMap<T> = { [K in keyof T]: keyof Pick<T, K> }
interface MyInterface {
a: string;
b: string;
}
当my类型的变量在类之外定义时,TypeScript很高兴:
const member: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
}
直接在抽象类或派生类中定义成员似乎是可行的。例如:
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('');
}
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('');
}
将成员更改为不同的类型也是如此:
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('');
}
为什么TypeScript在派生类之外工作并且没有标记为抽象时,会将派生类中成员的实现报告为错误
类成员是不考虑基类中的内容的类型,只有这样,才能检查派生类与基类的兼容性。由于成员是基于初始化值键入的,因此typescript不会对属性类型使用文字类型。只有某些地方TS不会加宽文字类型,而这不是其中之一 您所能做的最好的方法是为成员使用显式类型注释,正如您在问题中所说:
class DerivedClass extends BaseClass<MyInterface> {
protected member: KeyMap<MyInterface> = {
a: 'a',
b: 'b'
};
protected method = () => console.log('');
}