如何使用Immutable.js可选(TypeScript)记录类属性

时间:2017-03-24 09:27:32

标签: javascript typescript immutable.js

如果您尝试使用带有可选属性的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)。

如果我们想要一个可选属性,我们该如何解决这个问题?

打字稿版本:2.2.1

Immutable.js版本:4.0.0-rc-1

1 个答案:

答案 0 :(得分:3)

在推断超类的类型时,TypeScript不会查看子类主体。

func textViewDidBeginEditing(_ textView: UITextView) { moveTextView(textView, moveDistance: -250, up: true) } func textViewDidEndEditing(_ textView: UITextView) { moveTextView(textView, moveDistance: -250, up: false) } func textViewShouldReturn(_ textView: UITextView) -> Bool { textView.resignFirstResponder() return true } func moveTextView(_ textView: UITextView, moveDistance: Int, up: Bool) { let moveDuration = 0.3 let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance) UIView.beginAnimations("animateTextView", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(moveDuration) self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) UIView.commitAnimations() } 推断出超类的类型为Immutable.Record({ field: undefined })。因此,子类的类型与超类不兼容。

要解决此问题,您必须在超类声明类型信息,而不是子类:

Immutable.Record<{ field: undefined }>