[英]Dynamic class/interface in Typescript (w Angular)
我通过参数创建了一个带有动态 class 的 object。 有没有办法指定 object 的类型具有智能感知功能?
这是代码:
主要的:
let ita: any = new DynamicClass('ITA');
let deu: any = new DynamicClass('DEU');
Class 创建动态 class:
export class DynamicClass {
constructor(className: string) {
if (Store[className] === undefined || Store[className] === null) {
throw new Error(`Class type of \'${className}\' is not in the store`);
}
return new Store[className];
}
}
还有我的课:
export class ITA {
id: string;
name: string;
pck: string;
constructor() {
console.log('ITA class');
this.id = '1';
this.name = 'ita';
this.pck = '4';
}
}
export class DEU {
id: string;
name: string;
size: string;
constructor() {
console.log('DEU class');
this.id = '1';
this.name = 'ita';
this.size = '5';
}
}
export const Store: any = {
ITA,
DEU,
}
你可以投射它:
let ita: ITA = new DynamicClass('ITA') as ITA;
let deu: DEU = new DynamicClass('DEU') as DEU;
您可以创建工厂 function ,它将仅接受已知的 class 名称,其返回类型将根据提供的键(类名称)解析:
const Store = {
ITA,
DEU,
} as const;
type ClassMap = typeof Store;
const createClass = <Key extends keyof ClassMap>(key: Key) =>
new Store[key] as InstanceType<ClassMap[Key]>;
const instance = createClass('ITA'); // instance is of ITA type
createClass('foo'); // Error: '"foo"' is not assignable to '"ITA" | "DEU"'
我建议如下:
export const Store = {
ITA,
DEU,
};
let ita = new Store['ITA']; // ita type inferred to ITA
let deu = new Store['DEU']; // deu type inferred to DEU
let x = new Store['MISSING_PROP']; // does not compile
但我认为没有任何好处:
let ita = new ITA();
let deu = new DEU();
更新(澄清问题后)
为什么不为接受的语言定义联合类型,并使用 switch 语句:
type Langs = 'ITA' | 'DEU'
function doSth(lang: Langs): string {
switch (lang) {
case 'ITA':
const ita = new ITA();
return ita.name;
case 'DEU':
const deu = new DEU();
return deu.name + deu.size;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.