gpt4 book ai didi

javascript - 流类型: how to type dynamic classes factories

转载 作者:行者123 更新时间:2023-12-03 01:17:00 25 4
gpt4 key购买 nike

对于模糊的标题,我提前表示歉意,但我无法简洁地描述我的问题。

我有一个类Table,它采用动态Row类,用它来包装从类方法getRow()<返回的行。我的问题是,我无法在不丢失 getRow() 返回的类型的情况下使其正常工作。

这是我到目前为止所拥有的:

// @flow

class Row {
constructor() {}
};
class RowA extends Row {};
class RowB extends Row {};

class Table<RowType: Class<*>> {
Row: RowType;

constructor(RowClass: RowType = Row) {
this.Row = RowClass;
}

getRow() {
return new this.Row();
}
};

const a = new Table(RowA);
(a.getRow(): RowA);

const b = new Table(RowB);
(b.getRow(): RowB);

const c = new Table();
(c.getRow(): Row);

演示地址:https://flow.org/try/#0PTAEAEDMBsHsHcBQiDG0CGBnToBKDQBvRUU0FWAO0wBcAnAVxRtjoAoBKIgX0W4G5UGbHgQBBUAFMAHjUmUAJjnzwegtFmUIAQlNnylo1YQHINIgCroARtEkAeFRYCeAB0kAuUAGFhmewBUAHxBRCRkKl5ObpKC4aQU1PRMLOwqvppRCC7uoAC8RlzEZCWgNAAWAJaYAHQq+UYZ2IIlvPGgAOaSNCqcYaVkdN0MdJSglJKqFdV1CJwtZLymqFS0oOgNE6pWtpJsKmIcgmzoNV09cxxZ8IdxiWvWm5OgO3b7OkeIbNZn3b1XRm0nxWSXIT22NjenzYKF+F3gnGuRyAA

它返回的错误:

22: (a.getRow(): RowA);
^ Cannot cast `a.getRow()` to `RowA` because `RowB` [1] is incompatible with `RowA` [2].
References:
17: return new this.Row();
^ [1]
22: (a.getRow(): RowA);
^ [2]
25: (b.getRow(): RowB);
^ Cannot cast `b.getRow()` to `RowB` because `RowA` [1] is incompatible with `RowB` [2].
References:
17: return new this.Row();
^ [1]
25: (b.getRow(): RowB);
^ [2]

最佳答案

您必须使用声明的构造函数来实现接口(interface),或者使用(预定义的)构造函数来扩展类。RowInterfaceclass Rowclass Table 的模板参数中可以互换。

我还向 getRow() 方法添加了类型。另请参阅替代初始化(您不需要强制转换):

const a = new Table<RowA>(RowA);
let rA : RowA = a.getRow();

完整代码:

// @flow

interface RowInterface {
constructor():void;
}

class Row implements RowInterface {
constructor(){}
};

class RowA extends Row {
};
class RowB extends Row {
};

// bound to extend Row
//class Table<Entity: Row> {
class Table<Entity: RowInterface> {
_rowConstructor: Class<Entity>;

// take a constructor
constructor(row: Class<Entity>) {
this._rowConstructor = row;
}

// return a constructed entity
getRow(): Entity {
return new this._rowConstructor();
}
};


const a = new Table<RowA>(RowA);
let rA : RowA = a.getRow();

const b = new Table<RowB>(RowB);
(b.getRow(): RowB);

关于javascript - 流类型: how to type dynamic classes factories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51961660/

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