[英]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但是,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,
~~~~~~~~~
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.当您使用
TOOLTIP_PLACEMENTS.BOTTOM
您使用的是bottom
的值,它是一个字符串,因此这就是放置道具所期望的。
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.当你做
TOOLTIP_PLACEMENT.BOTTOM
你会得到它的值,它是小写字符串值的bottom
。 But keyof typeof TOOLTIP_PLACEMENT
gets you the keys which are the uppercase keys of the object: BOTTOM | TOP | RIGHT | LEFT
但是
keyof typeof TOOLTIP_PLACEMENT
您提供了对象的大写键的键: BOTTOM | TOP | RIGHT | LEFT
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];
为了获得键的值,您可以像这样定义放置类型:
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.然而,这取决于
StyleTippy
期望的属性。 I would assign it the type Placement
as defined before.我会为它分配之前定义的类型
Placement
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.