gpt4 book ai didi

javascript - 简单构造函数中的流类型错误

转载 作者:行者123 更新时间:2023-11-28 18:06:32 26 4
gpt4 key购买 nike

为什么 flowtype 报告以下错误以及需要如何记录该错误才能按预期工作?

index.js:7
4: console.log(MY_OBJECT.getName());
^^^^^^^ property `getName`. Property not found in
4: console.log(MY_OBJECT.getName());
^^^^^^^^^ new object

index.js

// @flow
import {MyObject} from './object';
const MY_OBJECT = new MyObject('name');
console.log(MY_OBJECT.getName());

对象.js:

// @flow
export function MyObject(name: string) {
this._name = name;
this.getName = function (): string {return this._name;};
this.setName = function (name: string) {this._name = name;};
}

最佳答案

Flow 不喜欢这种风格。当您在同一个模块中使用它时,它会工作,但是当您从另一个文件导入它时,它不会。

建议使用ES2015 class syntax相反:

// @flow
export class MyObject {
name: string;

constructor(name: string){
this.name = name;
}

getName() {
return this.name;
}

setName(name: string) {
this.name = name;
}
}

如果你不喜欢这个,你可以使用原型(prototype),即 has limited support :

// @flow
export function MyObject(name: string) {
this._name = name;
}

MyObject.prototype.getName = function (): string {return this._name;};
MyObject.prototype.setName = function (name: string) {this._name = name;};

关于javascript - 简单构造函数中的流类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454321/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com