import ErrorText from '@/components/shared/ErrorText'
import { Input } from 'antd'
import { InputProps } from 'antd/lib/input'
import styled from 'styled-components'
const StyledInput = styled(Input)``
const InputWrapper = styled.div`
margin: 15px 0;
`
function AntdInput({ text, isError, ...props }: { text: () =>
JSX.Element; isError: string[] }) {
const statusInput = isError?.[0]
return (
<InputWrapper>
{text && text()}
<StyledInput status={statusInput} {...props} />
<ErrorText>{isError?.length && isError[1]}</ErrorText>
</InputWrapper>
)
}
export default AntdInput
This is a reusable component using antd's Input and i am passing a isError paramerter which will be a string("warning" | "error"), but abtd input's status only allows type '"" | "warning" | "error" | undefined', how can I solve this problem??
CodePudding user response:
In your component isError
has the type string[]
which does not match the union of the type of the status
prop. One way so fix this would be changing the type of isError
to ("error" | "warning"[])
.
function AntdInput({ text, isError, ...props }:
{ text: () => JSX.Element; isError: ('error' | 'warning')[] }) { // change this
const statusInput = isError?.[0];
return (
<InputWrapper>
{text && text()}
<StyledInput status={statusInput} {...props} />
<ErrorText>{isError?.length && isError[1]}</ErrorText>
</InputWrapper>
);
}
If you have access to the type of status
you could also do
type Status = '' | 'error' | 'warning' | undefined;
type isError = Pick<{ [K in Status]: string }, 'error' | 'warning'>;
// --> "error" | "warning"
CodePudding user response:
You are declaring isError
as string[]
so TS is using that type.
You can either declare it as isError: ("warning" | "error")[]
, but I think that isError[0]
could be any string. Or you can use this type:
isError: [string] | [string, "warning" | "error"]
Notice: your isError?.length
check is not checking that the array has an element at position 1
.
A third option would be to just to a cast to "warning" | "error"
:
isError[1] as "warning" | "error"