![](/img/trans.png)
[英]TypeScript + React: defaultProps not works for optional props in strict null checking mode
[英]Can I disable distinguishing between null and undefined in TypeScript strict null-checking mode?
我目前正在将大型 TypeScript 代码库转换为严格的空检查。 代码库有许多带有可选成员的类型:
interface MyInterface {
member1?: number;
member2?: string;
}
此外,它使用类型Nullable<T> = T | null
Nullable<T> = T | null
,并且有很多return null
语句。
现在我面临许多编译器错误,这些错误基本上表明T | null
T | null
不能转换为T | undefined
T | undefined
,反之亦然,就像在这个例子中:
interface MyInterface {
member1?: number;
member2?: string;
}
const myFunction = () => {
return null;
}
const item: MyInterface = {};
item.member1 = myFunction(); // <== can't assign null to undefined
我喜欢 TypeScript 中的严格空检查,但我没有用null
和undefined
之间的区别。 我可以理解在某些用例中区分null
和undefined
是有意义的,但在这个项目中,它确实没有发挥重要作用。 这些return null
函数什么都不返回——它是null
还是undefined
都没有关系。 可选成员也是如此——它们要么被设置为一个值,要么不是。
我也宁愿不转换member1?: number;
对成员 1 member1: Nullable<number>;
, 并保持原样return null
我可以禁用undefined
和null
之间的区别,至少在 TypeScript 中吗?
我最好写一条评论,但由于我想向您展示一些代码示例,因此我将其作为答案。
如果我是你,我会为你的所有接口添加一些带有可选(弱)属性的包装器。
这是此类包装器的示例:
type MapNullable<T> = {
[P in keyof T]: undefined extends T[P] ? (T[P] | null) : T[P]
}
interface MyInterface {
member1?: number;
member2?: string;
}
const myFunction = () => {
return null;
}
const item: MapNullable<MyInterface> = {};
item.member1 = myFunction(); // member1?: number | null | undefined
MapNullable
遍历所有属性。 如果 property 是可选的,它只是使用另一种类型扩展此属性 - null
,如果 property 不是可选的,则保持原样。
我知道这不是最好的解决方案,但至少它可以帮助您进行迁移。 一旦迁移,您可以使您的类型更健壮并摆脱MapNullable
接口。
MapNullable
不是类型的最佳名称,但仍比Foo
或Bar
我同意@jcalz,我无法想象以其他方式处理 undefined|null 的其他方式
更新
看起来您的代码在 TS playground 中可以正常工作。 请看这里
我已经禁用了strictNullChecks
。 没有错误。
您应该明确设置函数的返回类型。
const myFunction = ():null => {
return null;
}
TS 版本:4.0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.