typescript 智能推导 fieldProps 代码怎么写?

typings.ts

type EnumFieldType = "number" | "input" | "select";
export interface INumber {
    value: number;
    ...
}
export interface IInput {
    value: string;
    ...
}
export interface ISelect {
    value: string[];
    ...
}
export interface IItem {
    type: EnumFieldType | "custom";
    // 根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect
    fieldProps?: unknown;
}

export interface IProps {
    name: string;
    data: IItem[];
}

index.tsx

const data:IProps={
  name:'components',
  data:[{
      type:'number',
    // 这里应该智能推导为 INumber
    fieldProps:{}
  },{
      type:'input',
    // 这里应该智能推导为 IInput
    fieldProps:{}
  },{
      type:'select',
    // 这里应该智能推导为 ISelect
    fieldProps:{}
  }];
}

想要的结果:根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect

阅读 1.8k
1 个回答

需要把IItem声明为union type

type EnumFieldType = "number" | "input" | "select";
export interface INumber {
    value: number;
}
export interface IInput {
    value: string;
}
export interface ISelect {
    value: string[];
}

export type IItem =
    | {
        type: 'number';
        // 根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect
        fieldProps?: INumber;
    }
    | {
        type: 'input';
        // 根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect
        fieldProps?: IInput;
    }
    | {
        type: 'select';
        // 根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect
        fieldProps?: ISelect;
    }
    | {
        type: 'custom';
        // 根据type的值,智能推导 fieldProps 为对应的 INumber、IInput、ISelect
        fieldProps?: unknown;
    }

export interface IProps {
    name: string;
    data: IItem[];
}

const data: IProps = {
    name: 'components',
    data: [{
        type: 'number',
        // 这里应该智能推导为 INumber
        fieldProps: { value: 1 }
    }, {
        type: 'input',
        // 这里应该智能推导为 IInput
        fieldProps: { value: '1' }
    }, {
        type: 'select',
        // 这里应该智能推导为 ISelect
        fieldProps: { value: ['1'] }
    }]
}

https://www.typescriptlang.or...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题