错误提示:
Type ‘(value: string | undefined) => string’ is not assignable to type ‘(displayValue: string | undefined) => 0 | 2 | 20’. Type ‘string’ is not assignable to type ‘0 | 2 | 20’.
代码示例:
<InputNumber
min={0}
max={20}
defaultValue={2}
style={{ margin: '0 16px' }}
formatter={(value) => `${value}px`}
parser={(value) => value!.replace('px', '')}
onChange={changeRadius}
/>
错误原因是因为formatter的参数类型number或者undefined,返回值是string类型。但是parser的参数类型是string和undefined,导致类型错误。
解决办法:
<InputNumber
min={0}
max={20}
defaultValue={2}
style={{ margin: '0 16px' }}
formatter={(value) => `${value}px`}
parser={parserRadius}
onChange={changeRadius}
/>
const parserRadius = (value: string | undefined) => {
value = value!.replace('px', '')
return Number(value)
}