首页 > 解决方案 > 如何动态解释对象的属性具有特定类型的TS

问题描述

沙箱中的代码示例:https ://codesandbox.io/s/typescript-playground-pzl2s

我遇到的问题对象有两种类型的属性。在某个时间点,从仅包含子属性的数据库中获取数据,DRI并根据父属性添加额外的子属性。

父属性和整个对象的类型定义如下:

type BalanceModelSectionType = {
  DRI: {
    AI: number;
    AMDR: {
      from: number;
      to: number;
      [index: string]: number;
    };
    EAR: number;
    RDA: number;
    UL: number;
    unit: string;
    [index: string]: string | number | object;
  };
  quantity: number;
  converted: {
    quantity: number;
    unit: string;
  };
  percentage: number;
};

type BalanceModelContainerSectionType = {
  DRI: {
    AI: number;
    AMDR: {
      from: number;
      to: number;
      [index: string]: number;
    };
    EAR: number;
    RDA: number;
    UL: number;
    SC: number;
    [index: string]: number | object;
  };
  percentage: number;
  accomplished: number;
};

type BalanceModelType = {
  alanine: BalanceModelSectionType;
  arginine: BalanceModelContainerSectionType;
  // ... many others
  [index: string]: BalanceModelSectionType | BalanceModelContainerSectionType;
};

在某个类型点收到以下对象,但它仍然缺少一些添加到其中的属性,forEach但会导致属性丢失的 TS 错误

const model: BalanceModelType = {
  alanine: {
    DRI: {
      AI: 0,
      AMDR: {
        from: 0,
        to: 0
      },
      EAR: 0,
      RDA: 0,
      UL: 0,
      unit: ``
    }
  },
  arginine: {
    DRI: {
      AI: 0,
      AMDR: {
        from: 0,
        to: 0
      },
      EAR: 0,
      RDA: 0,
      UL: 0,
      SC: 0
    }
  }
};

const defaultSectionValues = {
  quantity: 0,
  converted: {
    quantity: 0,
    unit: ``
  },
  percentage: 0
};
const progressSectionValues = {
  percentage: 0,
  accomplished: 0
};

Object.keys(model).forEach(sectionName => {
  const section = model[sectionName];

  /*
  How to dynamically explain TS that the property of the object has specific type? */
  if (sectionName === `alanine`) {
    model[sectionName] = { DRI: section.DRI, ...progressSectionValues }; // Property 'SC' is missing in type
  } else {
    model[sectionName] = { DRI: section.DRI, ...defaultSectionValues }; // Property 'unit' is missing in type
  }
});

如果您能建议一种更正确的方法来为对象提供类型,或者可能以有条件的方式处理类型,我将不胜感激?

标签: typescript

解决方案



type BalanceModelSectionType = {
  DRI: {
    AI: number;
    AMDR: {
      from: number;
      to: number;
      [index: string]: number;
    };
    EAR: number;
    RDA: number;
    UL: number;
    unit: string;
    [index: string]: string | number | object;
  };
  quantity?: number;
  converted?: {
    quantity: number;
    unit: string;
  };
  percentage?: number;
};

对可空字段使用问号


推荐阅读