A new union type has been defined:
type CustomParameterType = number | string | boolean | Array<number>;
An object is created to hold key-value pairs of this union type:
class CustomParameter
{
constructor(name: string, value: CustomParameterType)
{
this.Name = name;
this.Value = value;
}
public Name: string;
public Value: CustomParameterType;
}
An array of these CustomParameters can be used to store keys and values:
let customParams: Array<CustomParameter> = new Array<CustomParameter>();
customParams.push(new CustomParameter("one", 1));
customParams.push(new CustomParameter("two", "param2"));
By implementing a GetParameter
function, typed values can be retrieved from the array. Here's an example:
// should return a number with value 1
let numParam: number | undefined = this.GetParameter<number>("one", customParams);
// should return a string with value "param2"
let strParam: string | undefined = this.GetParameter<string>("two", customParams);
// should return undefined since 'two' is not of type number
let undefParam: number | undefined = this.GetParameter<number>("two", customParams);
However, there seems to be an issue with checking the generic type in the GetParameter function. It might require a type guarding function. Is it possible to resolve this?
Explore the example further in the TypeScript Playground: Playground