I am in this scenario where I don't know what a type will look like, whether it is undefined or a boolean, string or a number, etc. I am working on a library that will parse some string content and return an object of properties that the user has described using "type objects".
The Type is an interface for how the type objects should look like, and it goes like this:
/**
* A type object.
*/
export default interface IType<O>
{
/** The name of the type. */
name: string;
/** A description of the type. */
description?: string;
/**
* Parse the given input content and return the parsed output value.
* @param input The given input value.
* @returns The parsed output.
*/
parse(input: string): O;
}
I have provided the user with 3 pre-defined "type objects" that follow this interface (Number as numberType, Boolean as booleanType and String as stringType). The user can use these types to gather arguments from a string.
The argument interface defines how an argument should be specified in code.
/**
* An object describing how an argument will look like.
*/
export default interface IArg<T>
{
/**
* The name of the argument, this is how you use the argument later
* in the command object.
*/
name: string;
/** A description about the argument. */
description?: string;
/** The type the argument should be resolved with. */
type: IType<T>;
/** Should this take all the parameters left of the string? */
rest?: boolean;
/** Is the argument required? */
required?: boolean;
}
The user creates a command class and passes some arguments to the constructor including an array of arguments;
[
{
name: "age"
type: numberType
},
{
name: "name",
type: stringType
}
]
When the command string is parsed these arguments will be added into an object input.args. Somehow I want the typescript parser to know what may or may not be provided by the information given by the user.
E.g. if an argument is required and is a type of IArg<string> (let's call it name) then the parser knows that input.args.name is definetly a string, but if it isn't required, it might be undefined or a string.
Is this possible to achieve?
Edit: I found this answer by jcalz which takes an object of key-value pairs which does exactly what I'm looking for; but I'm unsure on how to implement it with arrays.