簡體   English   中英

打字稿:類型“字符串”不可分配給類型

[英]Typescript: Type 'string' is not assignable to type

我有一個對象

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

還有一個組件:

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

但是,Typescript 抱怨我向它發送了一個字符串文字

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

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


我將如何解決這個問題?

由於它們都是字符串,因此只需更改您的道具類型,以便放置是一個字符串。 當您使用TOOLTIP_PLACEMENTS.BOTTOM您使用的是bottom的值,它是一個字符串,因此這就是放置道具所期望的。

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

當你做TOOLTIP_PLACEMENT.BOTTOM你會得到它的值,它是小寫字符串值的bottom 但是keyof typeof TOOLTIP_PLACEMENT您提供了對象的大寫鍵的鍵: BOTTOM | TOP | RIGHT | LEFT BOTTOM | TOP | RIGHT | LEFT BOTTOM | TOP | RIGHT | LEFT 那不是字符串而是聯合類型。 為了獲得鍵的值,您可以像這樣定義放置類型: type Placement = typeof TOOLTIP_PLACEMENTS[keyof typeof TOOLTIP_PLACEMENTS]; 它返回所選鍵的值。 然而,這取決於StyleTippy期望的屬性。 我會為它分配之前定義的類型Placement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM