Typescript Init Dynamic Class Call By Name (2345)
How can I call a class without resorting to conditional statements? problem: (parameter) item: inputs Argument of type 'inputs' is not assignable to parameter of type 'ISelect &
Solution 1:
because the b
is a union of inputs you need to narrow it again in the map
function, unfortunately it's a limitation of typescript.
let a = b.map(item =>
item.type === 'inputSelect' ? new classes[item.type](item) :
item.type === 'inputText' ? new classes[item.type](item) :
undefined
);
or you can do a dynamic type check, then you need only 1 condition on any amount of interfaces in the inputs
union.
const checker = <T extends inputs>(item: T, cl: unknown): cl is ({new (a: T): InstanceType<(typeof classes)[T['type']]>}) => {
return classes[item.type] === cl;
};
let a = b.map(item => {
const cl = classes[item.type];
returnchecker(item, cl) ? newcl(item) : undefined;
}).filter((v): v is NonNullable<typeof v> => !!v);
Post a Comment for "Typescript Init Dynamic Class Call By Name (2345)"