I'm creating a custom Button
element in a React TS project, but when I declare the Props type
I receive the following error:
Type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>' is not assignable to type '"button" | "reset" | "submit" | undefined'.ts(2322)
index.d.ts(2086, 9): The expected type comes from property 'type' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'
I'm aware that there's an identical question (and I actually tried its solution by creating a custom enum
), but I still get the same error. I also tried using the type suggested in the error itself, as well as the types suggested in this GitHub issue, to no avail.
Given that both resources are over 2 years old, I'm wondering if something changed in that time or even if it's an issue to be tuned in my .tsconfig
file.
import React from 'react';
enum ButtonTypes {
'button',
'submit',
'reset',
undefined
}
type Props = {
text: string;
type: React.ComponentProps<'button'>; // ButtonTypes throws the same error
onClick: Function | null;
};
function Button({ text, type, onClick }: Props) {
return (
<button
className='className="bg-primary text-base-100 font-display font-light self-center mt-5 px-3 py-2"'
type={type}
>
{text}
</button>
);
}
export default Button;
CodePudding user response:
Personally Im surprised that the answer your mentioned is the approved one, because it still does throw ts errors for me.
Using the ButtonTypes
enum as:
enum ButtonTypes {
"button",
"submit",
"reset",
undefined
}
resolves to:
enum ButtonTypes {
"button" = 0,
"submit" = 1,
"reset" = 2,
undefined = 3
}
and of course it's incorrect because button
does not expect button type as 0
o 1
.
However after setting the values for enum fields:
enum ButtonTypes {
Button = 'button',
Submit = 'submit',
Reset = 'reset',
}
It works correctly.
Note: remember to change the type
prop type to ButtonTypes
.
type Props = {
text: string;
type?: ButtonTypes;
onClick: Function | null;
};
Note2: using enum is not necessary anyways, you can always extend your type with default button props.
type Props = {
text: string;
onClick: Function | null;
} & ButtonHTMLAttributes<HTMLButtonElement>;