I am writing a function that runs through a list of parameters looking for elements. If found, the function strips the name and returns the value, and if not there, a default. The values will be either a number or string. I would like a way to use the typescript generics, and the constraints to get the following to compile.
function GetValue<T extends number | string>(datum: string, element: string, defaultValue: T): T {
if (datum.startsWith(element)) {
if (typeof defaultValue === 'number')
return parseInt(datum.substring(element.length)); // error
else if (typeof defaultValue === 'string')
return datum.substring(element.length); // error
}
return defaultValue;
}
I've excluded any error checking code, e.g. from the parseInt. This would be called as;
console.log(GetValue("abc123", "abc", 456));
console.log(GetValue("abc123", "def", 456));
And expect to get out 123 and 456.
Currently, it fails on the lines // error since the function could be called with a type that is extends a string or number but is not a string or number.
How do I constrain the generic T such that it is limited to be either a string or number (and not the union string | number) and the return type is then matched to the type of the defaultValue?