如何防止 obj 属性上出现红色下划线

How to prevent red underline on obj properties

我在使用以下代码时遇到一些 linter 问题,我不明白为什么我允许日期作为字符串或 null 返回,但在返回字符串时会显示红色下划线。

static test(): { date: string | null, from: string | null, until: string | null } {

    let returnObj = { 
      date: null, 
      from: null, 
      until: null 
    };

    // Type 'string' is not assignable to type null
    returnObj.date = 'some string';

    return returnObj;
  }

重要提示:我不想使用@ts-ignore,因为我有多个类似的任务,所以对每个任务都有一个@ts-ignore 会使代码变得很丑陋。

谢谢!

我假设您使用的是 --noImplicitAny--strictNullChecks,因为这就是我使该错误发生的方式。

问题是 returnObj 中属性的推断类型是 null

您最好创建一个界面并使用它:

interface Stuff {
  date: string | null;
  from: string | null;
  until: string | null;
}

class Example {
  static test(): Stuff {
    let returnObj : Stuff = { 
      date: null, 
      from: null, 
      until: null 
    };

    returnObj.date = 'some string';

    return returnObj;
  }
}

另一种选择是对值使用单独的变量,然后在最后创建对象:

class Example {
  static test(): { date: string | null, from: string | null, until: string | null } {
    let date = null;
    let from = null;
    let until = null;

    date = 'some string';

    return { date, from, until };
  }
}

TypeScript 足够聪明,可以像那样更新函数内变量的推断类型。 (或者,当然,在变量上声明类型,这样就不必推断了。)