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

时间:2019-05-16 11:36:24

标签: typescript tslint

我的以下代码有一些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会使代码变得丑陋。

谢谢!

1 个答案:

答案 0 :(得分:2)

我假设您使用的是--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很聪明,可以像这样更新函数中变量的推断类型。 (或者,当然,可以在变量上声明类型,因此不必进行推断。)

相关问题