[英]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
接口,使size
為FontSize
類型(創建的枚舉):
interface TextProps {
size?: FontSize,
children: React.ReactNode;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.