【发布时间】: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