typescript - 如何防止 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 会使代码变得很快变得丑陋。
谢谢!
解决方案
我假设您正在使用--noImplicitAny
and --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 足够聪明,可以像这样更新函数中变量的推断类型。(或者,当然,声明变量的类型,这样它就不必推断了。)
推荐阅读
- python - 在 Python 中过滤具有特定要求的数据框
- android - 为什么我无法从 Firestore DocumentSnapshot 中获取 Int 类型?
- react-native - 运行 expo start 后的错误
- json - 当结构已知但不知道键时反序列化 JSON
- javascript - 从依赖项 package.json 运行 npm bin 脚本
- c - 如果有人在没有写任何东西的情况下进入,那么它应该终止
- python - 在扩展基于通用类的 CreateView 中访问和保存未包含在 fields 属性中的字段
- scala - Flink ProcessWindowFunction 的两个不同的包
- typescript - 如何从json传递数据并在listview中显示
- android - 在广播接收器中使用权限接收无法按预期工作