我试图构建类型和回调的映射,所以我从如下 struct 开始:
type Instantiable<T = unknown> = new (...args: any[]) => T;
type SingleParamFn<TInput = unknown, TOuput = unknown> = (arg: TInput) => TOuput;
type TypesRecord<T> = { type: Instantiable<T>, callback: SingleParamFn<T> };
type TypesMap = TypesRecord[]; // This is the structure
例如:
const myMap: TypesMap = [{ type: Date, callback: (value) => 'this is a Date' }];
这似乎像预期的那样工作,但我意识到这有点低效,因为需要循环数组以找到所需的类型.
我开始try 将这些类型作为对象键,至少在Google Chrome中是这样的:
class MyFancyObject {}
class MyOtherObject {}
const map = {
[Date]: () => 'this is a date',
[MyFancyObject]: () => 'this is a fancy object',
[MyOtherObject]: () => 'this is another object'
};
console.log(map[Date]()); // 'this is a date'
console.log(map[MyFancyObject]()); // 'this is a fancy object'
console.log(map[MyOtherObject]()); // 'this is another object'
const obj = new MyFancyObject();
console.log(map[obj.constructor]()); // 'this is a fancy object'
console.log(map[(new Date()).constructor]()); // 'this is a date'
我一直在判断一些文档,似乎一个对象的键只能是string or a Symbol,所以我判断了符号的组成,它似乎有点奇怪,因为它被定义为built-in object whose constructor returns a symbol primitive that's guaranteed to be unique,而对象的构造函数(据我所知)是唯一的.
考虑到所有这些,使用构造函数作为对象键是一种可靠的方法吗?如果是,如何定义此类对象的typescript类型?如果不是,是否还有其他选项(如Map
对象)?