[英]Type 'string' is not assignable
Here's how I define and use my type in my react app:以下是我在我的反应应用程序中定义和使用我的类型的方式:
FontSize.ts字体大小.ts
const fontSize = {
xs: 'xs',
sm: 'sm',
base: 'base',
lg: 'lg',
xl: 'xl'
}
export default Object.freeze(fontSize);
And this is my simple Text component:这是我的简单文本组件:
Text.tsx文本.tsx
import { FontSize } from '@bl/foundation';
interface TextProps {
size?: keyof typeof FontSize,
children: React.ReactNode;
}
const Text:React.FC<TextProps> = ({ size = FontSize.sm, children }) => {
const classNames = `font-size-${size}`;
return <p className={classNames}>
{children}
</p>
}
when I write my component:当我写我的组件时:
<Text size={FontSize.lg} > Some text here. </Text>
It show me in the size property this error:它在 size 属性中向我显示此错误:
Type 'string' is not assignable to type '"xs" | "sm" | "lg" | "xl" | "base" | undefined'.
Create an enum FontSize
(see below) to replace the fontSize
object.创建一个枚举
FontSize
(见下文)来替换fontSize
object。
Enum:枚举:
enum FontSize {
XS = "xs",
SM = "sm",
BASE = "base",
LG = "lg",
XL = "xl",
}
This also allows you to remove the Object.freeze
function call.这也允许您删除
Object.freeze
function 调用。
Then change the TextProps
interface so that size
is of type FontSize
(the enum created):然后更改
TextProps
接口,使size
为FontSize
类型(创建的枚举):
interface TextProps {
size?: FontSize,
children: React.ReactNode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.