What is the right way to let typescript know about props in shared component:
import styled from 'styled-components'
import React, { forwardRef } from 'react'
export const Input = forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<'input'>>(({ err, ...rest }, ref) => {
return <StyledInput {...rest} ref={ref} />
})
const StyledInput = styled.input`
box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
`
First issue:
Property 'err' does not exist on type 'Pick, HTMLInputElement>, "form" | "style" | "title" | "pattern" | "key" | "accept" | "alt" | "autoComplete" | ... 276 more ... | "onTransitionEndCapture"> & { ...; } & ThemeProps<...>'
Second issue: theme is of type any, but have an interface in provider:
You can create an type for your styled-components props:
type StyledInputProps = {
err?: string
}
const StyledInput = styled.input<StyledInputProps>`
// your styles...
`;
For your theme you have to create your own theme type. Example:
type ThemeType = {
colors: {
primary: string,
}
};
const theme: ThemeType = {
colors: {
primary: '#F47829',
}
};
const App = () => (
<ThemeProvider theme={theme}>
// ...
</ThemeProvider>
);
Documentation: https://www.styled-components.com/docs/api#typescript .
To pass your error into your 'Input'-component you have to create one more type for that one (alternatively you can use the same type if all props are the same):
type InputProps = {
err?: string
};
const Input: React.FC<InputProps> = forwardRef(({ ...rest }, ref) => {
return <StyledInput {...rest} ref={ref} />
});
Or using the type as the second type parameter for forwardRef
:
const Input = React.forwardRef<HTMLInputElement, InputProps>(({ ...rest }, ref)
=> <StyledInput {...rest} ref={ref} />);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.