如果您尝试使用带有可选属性的 Record
类,如下所示:
class MyRecord extends Immutable.Record({
field: undefined
}) {
field?: string;
}
...您会收到如下 TypeScript 错误:
ERROR in [at-loader] myFile.ts:x:y
TS2415: Class 'MyRecord' incorrectly extends base class 'Instance<{ field: undefined; }> & Readonly<{ field: undefined; }>'.
Type 'MyRecord' is not assignable to type 'Readonly<{ field: undefined; }>'.
Types of property 'field' are incompatible.
Type 'string | undefined' is not assignable to type 'undefined'.
Type 'string' is not assignable to type 'undefined'.
如果您像这样删除field
默认值:
class MyRecord extends Immutable.Record({}) {
field?: string;
}
...Typescript 不再提示,但是您无法在类实例上设置字段属性(因为 Record
API)。
如果我们想要一个可选属性,我们应该如何解决这个问题?
typescript 版本:2.2.1
Immutable.js 版本:4.0.0-rc-1
最佳答案
TypeScript 在推断父类(super class)的类型时不会查看子类主体。
从 Immutable.Record({ field: undefined })
推断出父类(super class)的类型成为Immutable.Record<{ field: undefined }>
。因此,子类的类型与父类(super class)不兼容。
要解决此问题,您必须在父类(super class)而不是子类中声明类型信息:
class MyRecord extends Immutable.Record<{
field?: string
}>({
field: undefined
}) { }
关于javascript - 如何拥有 Immutable.js 可选 (TypeScript) Record 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42995741/