首页 > 解决方案 > Dart 2 与 TypeScript 的 typeof 等价物是什么?

问题描述

我是 Dart 2 的新手。我希望一个类有一个属性。这是其他类的参考。它不是一个实例,而是类本身。在 TypeScript 中,可以编写如下。Dart 2中是否有相同的方法?

class Item { }

class ItemList {
    itemClass: typeof Item;
}

const itemList = new ItemList();
itemList.itemClass = Item;

更新:
我添加了更多上下文。以下是最小的示例代码。我想将实例化的角色委托给超类。

class RecordBase {
    id = Math.random();
    toJson() {
        return { "id": this.id };
    };
}

class DbBase {
    recordClass: typeof RecordBase;
    create() {
        const record = new this.recordClass();
        const json = record.toJson();
        console.log(json);
    }
}

class CategoryRecord extends RecordBase {
    toJson() {
        return { "category": "xxxx", ...super.toJson() };
    };
}

class TagRecord extends RecordBase {
    toJson() {
        return { "tag": "yyyy", ...super.toJson() };
    };
}

class CategoryDb extends DbBase {
    recordClass = CategoryRecord;
}

class TagDb extends DbBase {
    recordClass = TagRecord;
}

const categoryDb = new CategoryDb();
categoryDb.create();

const tagDb = new TagDb();
tagDb.create();

标签: dartdart-2

解决方案


我试图让你将示例代码放入 Dart。正如我之前所说,您无法获得对类的引用并在运行时基于此引用调用构造函数。

但是您可以引用构造类对象的方法。

import 'dart:math';

class RecordBase {
  static final Random _rnd = Random();

  final int id = _rnd.nextInt(100000);

  Map<String, dynamic> toJson() => <String, dynamic>{'id': id};
}

abstract class DbBase {
  final RecordBase Function() getRecordClass;

  RecordBase record;
  Map<String, dynamic> json;

  DbBase(this.getRecordClass);

  void create() {
    record = getRecordClass();
    json = record.toJson();
    print(json);
  }
}

class CategoryRecord extends RecordBase {
  @override
  Map<String, dynamic> toJson() {
    return <String, dynamic>{'category': 'xxxx', ...super.toJson()};
  }
}

class TagRecord extends RecordBase {
  @override
  Map<String, dynamic> toJson() {
    return <String, dynamic>{'tag': 'yyyy', ...super.toJson()};
  }
}

class CategoryDb extends DbBase {
  CategoryDb() : super(() => CategoryRecord());
}

class TagDb extends DbBase {
  TagDb() : super(() => TagRecord());
}

void main() {
  final categoryDb = CategoryDb();
  categoryDb.create(); // {category: xxxx, id: 42369}

  final tagDb = TagDb();
  tagDb.create(); // {tag: yyyy, id: 97809}
}

我不确定该create()方法是否应该被视为方法或构造函数。所以我选择让它成为一种更接近你的代码的方法。


推荐阅读