0

I want to define generic type T as predefined by me types. Below simple example can explain exacly what I mean. I need to get a function in which generic type T can be only number | string and this function should returns T | undefined.

export const getItemFromLocalStorage = <T extends number | string>(
  key: string,
  type?: 'number' | 'string'
): T | undefined => {
  const storedItem: string | null = localStorage.getItem(key)

  if (_.isNaN(storedItem)) {
    return undefined
  }

  if (_.isEqual(type, 'number')) {
    return _.toNumber(storedItem)
  }

  return _.toString(storedItem)
}

This version views an issue: 'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'string | number'.. And the same at _.toNumber method.

I also tried set <T = number | string>.

How can I achieve it with a TypeScript?

Thank you in advance.

Amaranthus
  • 11
  • 5

0 Answers0