Correct hashmap typing as function argument in TypeScript

331 views Asked by At

import React from 'react';
import styled from 'styled-components';

const IconWrapper = styled.Text`
  font-family: MyFont;
`;

const glyphs = {
  'logo': '\ue94e',
  'minus': '\ue900',
  'plus': '\ue901',
...
};

interface IconProps {
  glyph: string;
}

const Icon: React.FC<IconProps> = ({ glyph }) => {
  return (
    <IconWrapper>{glyphs[glyph]}</IconWrapper>
  );
};

export default Icon;

I need instead of glyph: string pass explicit type enum (or keyof glyphs). That could be probably enum but I don't want to duplicate the whole structure once again.

Thanks for your ideas

1

There are 1 answers

2
Eldar On BEST ANSWER

You can use keyof keyword combined with typeof to narrow down the type

const Icon = ({ glyph: keyof typeof glyphs }) => {

For readability, you can define another type like below :

type GlyphIcon  = keyof typeof glyphs;
const Icon = ({ glyph: GlyphIcon  }) => {