Refactoring 1 - 1. Type '...' is not assignable to type "..."
Type 'string' is not assignable to type '"text" | "outlined" | "contained" | undefined'." Resolving the error
<Button
onClick={handleLogin}
variant="contained"
>
LOGIN
</Button>
<Button onClick={handleGoogleLogin}>
<img
src={logoSrc}
alt="alternative image"
/>
<p>Social Login</p>
</Button>
Problem occurred
When rebuilding this code using maps in TypeScript, an error occurred.
Type 'string' is not assignable to type '"text" | "outlined" | "contained" | undefined'."
I was using the MUI and it was spitting out the error in the value of the variant property of the MUI Button. I struggled with this for a while and searched high and low through StackOverFlow and ChatGPT until I finally figured it out.
Solution.
type Variant = "text" | "outlined" | "contained" | undefined;
interface SubmitButtonProps extends ButtonProps {
variant?: Variant;
onClick?: () => Promise<void>;
contains?: React.ReactNode;
}
{loginButtonSettings.map(
({ onClick, contains, variant }: SubmitButtonProps, index: number) => (
<SubmitButton
key={index}
onClick={onClick}
contains={contains}
variant={variant}
/>
)
)}
As shown above, we need to predetermine the attribute values that will go into the variant through the value of type, and we also need to attach it to the interface. Actually, the next part is more important than this.
const loginButtonSettings = [
{
onClick: loginHandler,
contains: <div>Login</div>,
variant: "contained" as Variant, // 바로 여기!
},
As you can see, "contained" is generally recognized as a string, so we need to make sure that it is the value that was contained in the Variant property value!
댓글 작성
게시글에 대한 의견을 남겨 주세요.