簡體   English   中英

類型“字符串”不可分配

[英]Type 'string' is not assignable

以下是我在我的反應應用程序中定義和使用我的類型的方式:

字體大小.ts

    const fontSize = {
        xs: 'xs',
        sm: 'sm',
        base: 'base',
        lg: 'lg',
        xl: 'xl'
    }
    
    export default Object.freeze(fontSize);

這是我的簡單文本組件:

文本.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>
}

當我寫我的組件時:

<Text size={FontSize.lg} > Some text here. </Text>

它在 size 屬性中向我顯示此錯誤:

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

創建一個枚舉FontSize (見下文)來替換fontSize object。

枚舉:

enum FontSize {
    XS = "xs",
    SM = "sm",
    BASE = "base",
    LG = "lg",
    XL = "xl",
}

這也允許您刪除Object.freeze function 調用。

然后更改TextProps接口,使sizeFontSize類型(創建的枚舉):

interface TextProps {
    size?: FontSize,
    children: React.ReactNode;
}

暫無
暫無

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

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