ts 如何继承父类并修改属性?

ts 如何继承父类并修改属性?

image.png
image.png

相关代码


export interface ITableData {
    flag: 0 | 1
    measure_name: string
    measure_value: number
    result_desc: string
    standard_deviation: number
    standard_value: number
    name: string
}

interface IMeasureData extends ITableData {
    measure_value: number | string
}

const measureList: IMeasureData[] = [{ measure_value: "2" }]
阅读 2.3k
3 个回答
✓ 已被采纳

可以使用工具类型 Omit 将需要修改的属性 measure_value 剔除掉,然后继承剔除后的接口,并对该属性进行重新声名。(PS:如下代码中,我将原接口的属性改成可选属性,以避免赋值时的报错。)

export interface ITableData {
  flag?: 0 | 1;
  measure_name?: string;
  measure_value?: number;
  result_desc?: string;
  standard_deviation?: number;
  standard_value?: number;
  name?: string;
}

interface IMeasureData extends Omit<ITableData, "measure_value"> {
  measure_value: number | string;
}

const measureList: IMeasureData[] = [{ measure_value: "2" }];

希望对题主有所帮助!

export interface ITableData<T = number> {
  flag: 0 | 1;
  measure_name: string;
  measure_value: T;
  result_desc: string;
  standard_deviation: number;
  standard_value: number;
  name: string;
}

const measureList: Partial<ITableData<number | string>>[] = [{ measure_value: "2" }];

我提出两个点吧:

1. 充分使用泛型
2. 结合Partial实现可选参数
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏