Home > Back-end >  Type 'string' is not assignable
Type 'string' is not assignable

Time:07-26

Here's how I define and use my type in my react app:

FontSize.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

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:

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

CodePudding user response:

Create an enum FontSize (see below) to replace the 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.

Then change the TextProps interface so that size is of type FontSize (the enum created):

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