A few days back, I posted a question regarding the transformation of an array of objects into a single object while preserving their types. Unfortunately, the simplified scenario I provided did not resolve my issue.
In my situation, there are two classes: Int
and Bool
, both of which are subclasses of the Arg
class. Additionally, there exist two factory functions called createInt
and createBool
.
class Arg<Name extends string> {
protected name: Name
public constructor(name: Name) {
this.name = name
}
}
class Int<Name extends string> extends Arg<Name> {}
class Bool<Name extends string> extends Arg<Name> {}
const createInt = <Name extends string>(name: Name) => new Int<Name>(name)
const createBool = <Name extends string>(name: Name) => new Bool<Name>(name)
Now, I aim to define arguments (Int
or Bool
with specific names) in an array and create a function that accepts mapped types of these arguments (Number
for Int
, Boolean
for Bool
) as input.
const options = {
args: [
createInt('age'),
createBool('isStudent')
],
execute: args => {
args.age.length // This should trigger an error stating that property 'length' does not exist on type 'number'.
args.name // This should produce an error since property 'name' doesn't exist in 'args'.
args.isStudent // This should work fine as it is a boolean.
}
}
I came across a question related to mapping types, but I'm unsure how to map the array of `args` to an object of `args`, thereby losing information about argument types. At the moment, I only have strings there without maintaining details about argument types.
type Options = {
args: Arg<string>[],
execute: (args: Record<string, any>) => void
}
Is there a way to achieve this and retain the argument types within the execute function? You can access a demo here.