【问题标题】:Is there a way to sort an array with nullable properties in typescript?有没有办法在打字稿中对具有可为空属性的数组进行排序?
【发布时间】:2021-09-22 16:50:42
【问题描述】:

这是我的代码:

export function getExpertTitle(
  experiences: Array<{
    title?: string | null;
    description?: string | null;
    endDate?: Date | null;
  }> | null
) {
  const emptyExperience = {
    title: null,
    description: null,
    endDate: null
  };

  let currentExperience = experiences && experiences[0];
  
  // Here is were i start to have the error
  // Object is possibly 'null' or 'undefined'.ts(2533)  

  for (let i = 0, l = experiences && experiences.length; i < (!isNullOrUndefined(l) && l); i++) {
    if (isNullOrUndefined(experiences && experiences[i].endDate)) {
      currentExperience = experiences && experiences[i];
    } else if ((!isNullOrUndefined(currentExperience) && currentExperience.endDate.getTime()) > Date.now()) {
      currentExperience = experiences && experiences[i];
    }
  }

所以,我想做的是比较 experiences 数组并使用 endDate 属性按日期对它们进行排序,我想设置 currentExperience 作为最新体验。此外,如果 endDate 属性为“null”,则体验仍在进行中,这使其成为默认的 currentExperience

我在想 for 循环可能看起来像这样,但我仍然收到错误:

  for (let i = 0, l = experiences.length; i < l; i++) {
    if (isNullOrUndefined(experiences[i].endDate)){
      currentExperience = experiences && experiences[i];
      break;
    }
    else if (experiences[i].endDate?.getTime() > currentExperience.endDate.getTime()) {
      currentExperience = experiences && experiences[i];
    }
  }

我还在努力解决这个问题,如果我找到解决方案,我会发布它。 同时,任何 cmet 都会受到赞赏。

【问题讨论】:

  • 基于错误,特别是ts(2533),并且您有类型定义,这应该是一个 Typescript 问题(而不是 Javascript)。我建议更改标签以匹配此内容。
  • 谢谢!我会更新的。

标签: arrays typescript sorting null


【解决方案1】:

此错误的原因是您对数组的类型定义说任何条目都可能为空:

experiences: Array<{
    title?: string | null;
    description?: string | null;
    endDate?: Date | null;
  }> | null // <------------------ HERE

要过滤掉 null 值,您可以使用类似

experiences.filter(x => x !== null) as Array<{
  title?: string | null;
  description?: string | null;
  endDate?: Date | null; }> // array cannot contain null, only objects with null properties

但从你的代码正在做的事情来看,我认为你更喜欢在你的 for 循环中使用这样的东西:

  for (let i = 0, l = experiences.length; i < l; i++) {
    // below is now true if the object is null
    if (isNullOrUndefined(experiences && experiences[i] && experiences[i].endDate)){
      currentExperience = experiences && experiences[i];
      break;
    }
    // ...
  }

【讨论】:

    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多