我们可以在TypeScript中创建std :: type_index吗?

时间:2020-05-01 15:20:03

标签: c++ typescript types typescript-generics

在C ++中,有一个不错的std::type_index,它将类型转换为可以存储在映射中或用于相等性测试或类似事物的值,例如:

std::unordered_map<std::type_index, std::vector<void *>> instances;

class A { /* stuff... */ };
class B { /* stuff... */ };

template <typename Type>
void insert(Type *type) {
    type_names[std::type_index(typeid(Type))].push_back(&type);
}

insert<A>(new A());
insert<B>(new B());

有没有办法在TypeScript中做同样的事情?可能的解决方案如下所示:

const instances: Record<string, any[]> = {};

function insert<T>(inst: T): T {
    const tid: string = ???;
    if (!instances[tid]) {
        instances[tid] = [];
    }
    instances[tid].push(inst);
}

从更正式的意义上讲,我希望函数type_index<T>(): string使得type_index<A>() === type_index<B>()当且仅当类型A和类型B相等时

0 个答案:

没有答案