0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.