开发者社区> 问答> 正文

typescript的接口可选属性与条件类型组合问题

interface IFormConfigItem {  
  // 表单的title  
  label: string;
  // 表单的变量名
  name: string;
  // 表单项的类型
  type?: 'input' | 'inputNumber' | 'select' | 'textarea' | 'month' | 'custom';
  // 表单是select时的选择项
  options?: ISelectItem[];
  // 表单是inputNumber时的最大值,可选
  max?: number;
  // 枚举值code与desc的映射,用于返显
  enumLabels?: Record<string, string>;
  // 是否非必填
  isOptional?: boolean;
}

我的问题: 如果type取值为select,那么options由可选属性变为必须有的属性,该怎么修改这个接口?

展开
收起
问问小秘 2020-01-09 16:03:06 626 0
1 条回答
写回答
取消 提交回答
  • ype TypeProps = 'input' | 'inputNumber' | 'select' | 'textarea' | 'month' | 'custom';

    type SelectItem = { type?: Extract<TypeProps, 'select'>, options: ISelectItem[]; }

    type NonSelectItem = { type?: Exclude<TypeProps, 'select'>; options?: ISelectItem[]; }

    type FormConfigItemProps = SelectItem | NonSelectItem;

    type IFormConfigItem = { // 表单的title label: string; // 表单的变量名 name: string; // 表单是inputNumber时的最大值,可选 max?: number; // 枚举值code与desc的映射,用于返显 enumLabels?: Record<string, string>; // 是否非必填 isOptional?: boolean; } & FormConfigItemProps;

    2020-01-09 16:06:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
现代TypeScript高级教程 立即下载
继承与功能组合 立即下载
重新定义计算的边界 立即下载