How to limit a typescript generic to one of two primitives?

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 os 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;

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 to I constrain the generic T such that it is limited to be either a string or number and the return type is then matched to the type of the defaultValue?

Read more here:

Content Attribution

This content was originally published by Niall at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: