我想创建需要可选参数之一的函数类型。
据我所知,是制作条件类型,但问题是在函数打字稿中无法根据此条件缩小类型
type a = { propA: number };
type b = { propB: string };
type OneOfIsRequired = <T extends a | undefined, S extends b | undefined>
(parameterOne: S extends undefined ? a : T, parameterTwo?: T extends undefined ? b : S, x: number) => any;
const fn: OneOfIsRequired = (a, b) => {
if (a) {
const propA = a.propA;
} else {
const propB = b.propB; // Object is possibly 'undefined'.. typescript can not narrow …Run Code Online (Sandbox Code Playgroud) 我有带输入的蚂蚁设计表单,我需要限制一些字符在输入中写入。
<Form.Item
{...formItemLayout}
label={this.props.intl.formatMessage({ id: 'customer.form.zipCode' })}
>
{getFieldDecorator('zip_code', {
validateTrigger: 'onBlur',
initialValue: this.props.addressFormDefaults ? this.props.addressFormDefaults.zip_code : '',
rules: [
{
transform: (value) => typeof value === 'string' ? value.trim() : undefined,
required: true, message: this.props.intl.formatMessage({ id: 'validation.requiredField' }),
},
],
})(
<Input
type="number"
size="large"
className={this.props.useSmartForm ? `${this.props.smartFormClassInstance} ${SMARTFORM_CLASS.ZIP}` : undefined}
form={this.props.formId}
disabled={this.props.formDisabled}
/>,
)}
</Form.Item>
Run Code Online (Sandbox Code Playgroud)
所以理想的解决方案是添加一些按键事件并验证它
<Input
type="number"
onKeyDown={(event) => {
// some validation;
if (someValidation()) {
return true;
}
return false;
}}
/>;
Run Code Online (Sandbox Code Playgroud)
但从 ts 定义
onKeyPress?: KeyboardEventHandler<T>; …Run Code Online (Sandbox Code Playgroud)