class __Constants__ {
[key: string]: string;
constructor(values: string[]) {
values.forEach((key) => {
this[key] = key;
});
}
}
const Constants = __Constants__ as {
new <T extends readonly string[]>(values: T): { [k in T[number]]: k };
};
const __colors__ = ["BLUE", "GREEN"] as const;
const Colors = new Constants(__colors__);
// const Colors: {
// BLUE: "BLUE",
// GREEN: "GREEN",
// }
是否可以键入 __Constants__
类,使其具有与强制转换相同的返回类型,但不使用自定义构造函数签名?
编辑:请注意,我正在将旧版 JS 代码库转换为 Typescript,并希望尽可能少地更改 JS 代码。真正的 Constants
类更复杂,这里我已经隔离了我当前面临的问题。
答案 0 :(得分:0)
它是这样工作的:
const Constants = class {
[key: string]: string;
constructor(values: string[]) {
values.forEach((key) => {
this[key] = key;
});
}
} as {
new <T extends readonly string[]>(values: T): { [k in T[number]]: k };
};
const __colors__ = ["BLUE", "GREEN"] as const;
const Colors = new Constants(__colors__);
它使用所谓的“类表达式”
编辑:我尝试了其他的东西。为什么不使用函数而不是类?这有效:
function Constants<T extends readonly string[]>(values: T): { [k in T[number]]: k } {
const obj: any = {};
values.forEach((key) => {
obj[key] = key;
});
return obj;
}
当然你必须像函数一样调用它,而不是创建一个类实例:
const __colors__ = ["BLUE", "GREEN"] as const;
const Colors = Constants(__colors__); // don't use "new" here