Home > Back-end >  What is the return type of the function in typescript
What is the return type of the function in typescript

Time:11-24

I have this function

 export const getColor = (color: string): string => colors[color] || colors.white;

but I get warning line under colors[color] || colors.white saying that Unsafe return of an any typed value I made sure that this method accepts string and returns string but I don't know what is the exact problem it's forbidden to use any

export const colors = {
  'dark-grey': '#606060',
  'light-grey': '#909090',
  'slate-grey': '#7889a0',
  'olive-green': '#8fd683',
  'light-blue': '#0371ff',
  'dark-gray': '#4b6c89',
  'blue-700-new': 'var(--color-brand-primary-default-new)',
  azure: '#1676ff',
  blue: '#1676ff',
  white: '#fff',
  black: '#000',
  brandPrimaryDefault: 'var(--color-brand-primary-default-new)',
  brandPrimaryLight: 'var(--color-brand-primary-light-new)',
  naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',
};

CodePudding user response:

Try to specify the type of the colors object items:

export const colors: { [key: string]: string; } = {
  'dark-grey': '#606060',
  'light-grey': '#909090',
  'slate-grey': '#7889a0',
  'olive-green': '#8fd683',
  'light-blue': '#0371ff',
  'dark-gray': '#4b6c89',
  'blue-700-new': 'var(--color-brand-primary-default-new)',
  azure: '#1676ff',
  blue: '#1676ff',
  white: '#fff',
  black: '#000',
  brandPrimaryDefault: 'var(--color-brand-primary-default-new)',
  brandPrimaryLight: 'var(--color-brand-primary-light-new)',
  naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',
};

Link to playground.

CodePudding user response:

Your colors object expects specific keys to be used as an index, not just any string. You will want to use a union of the possible colours instead of string. For example:

export const colors = {
  'dark-grey': '#606060',
  'light-grey': '#909090',
  'slate-grey': '#7889a0',
  'olive-green': '#8fd683',
  'light-blue': '#0371ff',
  'dark-gray': '#4b6c89',
  'blue-700-new': 'var(--color-brand-primary-default-new)',
  azure: '#1676ff',
  blue: '#1676ff',
  white: '#fff',
  black: '#000',
  brandPrimaryDefault: 'var(--color-brand-primary-default-new)',
  brandPrimaryLight: 'var(--color-brand-primary-light-new)',
  naturalGrayDarker2: 'var(--color-natural-gray-darker-2)',
};

export type Color = keyof typeof colors // 'dark-grey' | 'light-grey' | ...
export const getColor = (color: Color): string => colors[color] || colors.white;

TypeScript Playground

  • Related