我有一个组件,它有3个props :toValue
,fromValue
,children
.前两个是可选的,但如果指定了其中一个,则还必须指定另一个.children
属性是一个具有inputProps
参数的函数,如果指定,它应该等于toValue
函数的返回类型(TInputValue
)或TStateValue
.
我编写了以下代码,但我不明白为什么在指定了toValue
函数的情况下,inputProps
是any
.如何修复它?
interface IP<T> {
value: T
onChange: (value: T) => void
}
interface A<TStateValue> {
toValue?: never
fromValue?: never
children: (inputProps: IP<TStateValue>) => null
}
interface B<TStateValue, TInputValue> {
toValue: (value: TStateValue) => TInputValue
fromValue: (value: TInputValue) => TStateValue
children: (inputProps: IP<TInputValue>) => null
}
type C<TStateValue, TInputValue> =
| A<TStateValue>
| B<TStateValue, TInputValue>
const propsWithoutToValue: C<number, string> = {
children: (inputProps) => null, // `inputProps` is `IP<number>`. Nice!
}
const propsWithToValue: C<number, string> = {
toValue: (value) => value.toString(), // The return type is a `string`, so the `inputProps` must be `IP<string>`
fromValue: (value) => Number(value),
children: (inputProps) => null, // `inputProps` is any, but must be `IP<string>`. How to fix it?
}
我已经为我正在努力解决的问题创建了回购:https://github.com/oxilor/form-types