首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类型“string”不可分配

类型“string”不可分配
EN

Stack Overflow用户
提问于 2022-07-26 08:43:02
回答 1查看 216关注 0票数 1

下面是我如何在自己的react应用程序中定义和使用我的类型:

FontSize.ts

代码语言:javascript
运行
复制
    const fontSize = {
        xs: 'xs',
        sm: 'sm',
        base: 'base',
        lg: 'lg',
        xl: 'xl'
    }
    
    export default Object.freeze(fontSize);

这是我的简单文本组件:

Text.tsx

代码语言:javascript
运行
复制
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>
}

当我编写组件时:

代码语言:javascript
运行
复制
<Text size={FontSize.lg} > Some text here. </Text>

它在size属性中显示了这个错误:

Type 'string' is not assignable to type '"xs" | "sm" | "lg" | "xl" | "base" | undefined'.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-26 08:49:15

创建一个枚举FontSize (参见下面)来替换fontSize对象。

Enum:

代码语言:javascript
运行
复制
enum FontSize {
    XS = "xs",
    SM = "sm",
    BASE = "base",
    LG = "lg",
    XL = "xl",
}

这还允许您删除Object.freeze函数调用。

然后更改TextProps接口,使size的类型为FontSize (创建的枚举):

代码语言:javascript
运行
复制
interface TextProps {
    size?: FontSize,
    children: React.ReactNode;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73120269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档