首页 > 解决方案 > 如何防止 obj 属性上的红色下划线

问题描述

我在使用以下代码时遇到了一些 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 会使代码变得很快变得丑陋。

谢谢!

标签: typescripttslint

解决方案


我假设您正在使用--noImplicitAnyand --strictNullChecks,因为这就是我可以使该错误发生的方式。

问题是推断的属性类型returnObjnull.

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

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 足够聪明,可以像这样更新函数中变量的推断类型。(或者,当然,声明变量的类型,这样它就不必推断了。)


推荐阅读