【问题标题】:TypeError: class.function is not a function. (In 'classname.function(param)')TypeError:class.function 不是函数。 (在 'classname.function(param)' 中)
【发布时间】:2020-03-24 23:55:55
【问题描述】:

我不是 JavaScript 专家,但按照 Java 和其他语言的逻辑,以下应该可行,但不行:

//* @flow */

class Assets {
  parts: Array<PartsItem>;

  constructor() {
    this.parts = [];
  }

  merge(other: Assets) {
    this.parts = this.parts.concat(other.parts);
  }
}

class PartsItem {
  name: string;
}

function addNewAssets(assets: Assets, newAssets: Assets) {
  // the out log verifies that both assets are having all expected values and expected structure
  console.log("adding ", newAssets);
  console.log("to ", assets);
  assets.merge(newAssets);
  return assets;
}

function run_example() {
  let item1: PartsItem = new PartsItem();
  item1.name = "part1";
  let item2: PartsItem = new PartsItem();
  item2.name = "part2";

  let assets = new Assets();
  let otherAssets = new Assets();

  assets.parts.push(item1);
  otherAssets.parts.push(item1);

  let mergedAssets = addNewAssets(assets, otherAssets);

  console.log(JSON.stringify(mergedAssets));
}

run_example();

调用 addNewAssets 时,我希望得到合并的资产,但结果是:

[12:06:55] W | ReactNativeJS ▶︎ Possible Unhandled Promise Rejection (id: 0):
                             │ TypeError: assets.merge is not a function. (In 'assets.merge(newAssets)', 'assets.merge' is undefined)

和JS“不可预测”有什么关系这个?

【问题讨论】:

  • 在我看来这不像 JavaScript。是打字稿吗?
  • "当调用 addNewAssets" — 你没有在你提供的代码中调用它。你需要一个minimal reproducible example
  • @Quentin:它的 JavaScript with Flow
  • @Quentin:您可以在以下位置运行代码示例:flow.org/try
  • 刚刚检查了问题中的代码,它按预期工作。唯一的事情是:而不是this.parts.concat(other.parts) 我希望this.parts = this.parts.concat(other.parts);

标签: javascript reactjs typescript flowtype ecmascript-5


【解决方案1】:

即使一些非常聪明的人降低了这个问题的等级,它也展示了 JS 类和 Flow 的一个陷阱。

由于资产在从 JSON 回读后已被使用,因此某些类信息丢失了,即使已键入字段,Flow 也不是 Java,也不是硬类型。

我需要试试这个:https://github.com/STRML/json-to-flow 或https://www.npmjs.com/package/flow-validator,如此处所述: How can I get JSON.parse result covered by the Flow type checker?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 2012-02-05
    • 2010-11-11
    • 2017-07-07
    • 2014-11-09
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多