简体   繁体   中英

Typescript: Type 'string' is not assignable to type

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?

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

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 BOTTOM | TOP | RIGHT | LEFT 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM