【问题标题】:How to type a function that transforms some properties of an input object如何键入转换输入对象的某些属性的函数
【发布时间】:2020-03-24 00:34:01
【问题描述】:

有谁知道如何键入一个转换函数,其中只有部分键是已知的/相关的,并且已知键之一是可选的?例如

const transform = <T extends BaseAkpiDto>(akpiDTO: T) => {
  const { startDate, periodData, ...akpiBase } = akpiDTO;
  const withMoments = {
    ...akpiBase,
    startDate: moment.utc(startDate),
  };

  if (!periodData) {
    return withMoments;
  }

  return {
    ...withMoments,
    lineData: akpiDtoToLineData(withMoments.startDate, periodData),
  };
};

interface BaseAkpiDto {
  startDate: string;
  endDate: string;
  periodData?: PeriodDto[];
}

const test: WithPeriodData = akpiDTOtoAkpiData({
  id: 1,
  name: 'my name',
  startDate: '2019',
  periodData: [] as PeriodDto[],
});

interface WithPeriodData {
  id: number;
  name: string;
  startDate: Moment;
  lineData: Period[];
}

当(且仅当)输入上有 lineData 属性时,我无法让返回类型包含 lineData 属性:(

Typescript 向我的 testvariable 抱怨以下消息:

'Pick & { 开始日期:时刻;结束日期:时刻; }' 但 在“WithPeriodData”类型中是必需的。

【问题讨论】:

  • 您能否删除所有那些未知/时刻类型并使用test 变量添加调用,该错误发生在哪里?

标签: typescript typescript-typings typescript-generics


【解决方案1】:

函数transform 具有条件行为。查看它可以返回或不包含lineData 的控制流。因此,您不能分配作为联合的返回 IHaveLineData | IDoNotHaveLineData 到 IHaveLineData 因为返回只是更宽的类型。想象一下,您想将string | number 的smth 分配给number,原因与您不能这样做的原因相同。

为确保获得所需的结构,您需要附加额外的控制流以确保类型。所以只是:

// at this level test is infered as with or without lineData
const test= akpiDTOtoAkpiData({
  id: 1,
  name: 'my name',
  startDate: '2019',
  periodData: [] as PeriodDto[],
});

if ('lineData' in test) {
  // here test is precisely the type with lineData
}

【讨论】:

  • 我希望它可以通过 2.8 中添加的泛型和条件类型来解决,但这可能是不可能的,就像你说的 :(
猜你喜欢
  • 2022-08-17
  • 2013-07-29
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多