Home > Mobile >  Typescript: Type 'string' is not assignable to type
Typescript: Type 'string' is not assignable to type

Time:11-05

I have an object

export const TOOLTIP_PLACEMENTS = Object.freeze({
  TOP: 'top',
  BOTTOM: 'bottom',
  LEFT: 'left',
  RIGHT: 'right',
});

And a component:

type Props = {
  text?: string;
  children: React.ReactNode;
  placement?: keyof typeof TOOLTIP_PLACEMENTS;
};

const Tooltip = ({
  text,
  children,
  placement = TOOLTIP_PLACEMENTS.BOTTOM,
}: Props) => (
  <StyleTippy
    content={<TitleContainer>{text}</TitleContainer>}
    placement={placement}
    arrow={true}
  >
    {children}
  </StyleTippy>
);

However, Typescript is complaining that I am sending it a string literal

src/components/Tooltip.tsx:41:3 - error TS2322: Type 'string' is not assignable to type '"TOP" | "BOTTOM" | "LEFT" | "RIGHT"'.

41   placement = TOOLTIP_PLACEMENTS.BOTTOM,
     ~~~~~~~~~


How would I fix this?

CodePudding user response:

when you do TOOLTIP_PLACEMENT.BOTTOM you get its value, which is bottom the lowercase string value. But keyof typeof TOOLTIP_PLACEMENT gets you the keys which are the uppercase keys of the object: BOTTOM | TOP | RIGHT | LEFT. that are not strings but a union type. In order to get the value of a key you can define a type for placement like this: type Placement = typeof TOOLTIP_PLACEMENTS[keyof typeof TOOLTIP_PLACEMENTS]; which returns the value of the selected key. However this depends on the property StyleTippy expects. I would assign it the type Placement as defined before.

CodePudding user response:

Since they are all strings just change your props types so that placement is a string. When you use TOOLTIP_PLACEMENTS.BOTTOM you are using the value of bottom which is a string so that is whats what the placement prop is expecting.

type Props = {
  text?: string;
  children: React.ReactNode;
  placement?: string;
};
  • Related