I want to create a object use a json object like
const data = {type :'A', param: [1,2]}
so I can call
const i:A = create(data)
I wish compiler can check whether the type string and param array be matched
what I already got is like:
const Ctors = {
A: class {
constructor(a: number, b: number) { }
},
B: class {
constructor(s: string) { }
}
};
type keys = keyof typeof Ctors;
function create<K extends keys>(k: K, ...p: ConstructorParameters<typeof Ctors[K]>) {
return new Ctors[k](...p);
}
create('A', 1, 2);
create('B', 's')
the only problem is I had to modify
return new Ctors[k](...p);
to return new (Ctors[k] as any)(...p);
or there will be an error:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
I can live with an ‘as any’ but it seems not make sense, I want to know why and if there is a way to avoid it
user24597198 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.