[FIXED] Typescript: return a value depends on generic type

Issue

I need to make this logic work.

const defaultNumberOption = {
  label: 'Select',
  value: 0,
};

const defaultStringOption = {
  label: 'Select',
  value: '',
};

const getDefaultOption = <ValueType extends string | number>(): IOption => {
  // if ValueType is 'string' - return defaultStringOption 
  // if ValueType is 'number' - return defaultNumberOption 
}

I tried to use different approaches, but with each of them had the same problem: I can’t find a way to make a structure with types in condition, but with values in expression.

If there is a way to do it – it would be great.

Solution

You could use conditional types to achieve this.

interface DefaultNumberOption {
    label: 'Select',
    value: number,
}

interface DefaultStringOption {
    label: 'Select',
    value: string,
}

type DefaultOption<T extends number | string> = T extends string
    ? DefaultStringOption
    : DefaultNumberOption

const getDefaultOption = <T extends number | string>(value: T): DefaultOption<T> => {
    if (typeof value === 'string') {
        return {
            label: 'Select',
            value: ''
        } as DefaultOption<T>;
    }
    return {
        label: 'Select',
        value: 0
    } as DefaultOption<T>;
}

let x = getDefaultOption(''); // x will have type DefaultStringOption
let y = getDefaultOption(0); // y will have type DefaultNumberOption

Here is a link to a TS playground if you want to play around with the solution.

Answered By – Palladium02

Answer Checked By – Laura B. (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published