[英]Object is possibly “null” - error with TypeScript linter
I have a question about TypeScript! 我有关于TypeScript的问题! We're doing a JSX to TypeScript conversion across our projects. 我们正在整个项目中进行JSX到TypeScript的转换。
{instances.map(instance => {
const { id, name, type } = second;
const pageUrl = makePath(
routes.page.path,
{ firstId: first.id , secondId: id }, <<<<<<
);
On the line with "<<<<<<", "first" of "first.id" is highlighted with the following error: 在带有“ <<<<<<<”的行上,“ first.id”的“ first”突出显示,并出现以下错误:
Object is possibly 'null'.
I'm unsure how to define it to where it wouldn't be considered null. 我不确定如何将其定义为不会被视为null的地方。 I was able to figure out the second one through destructuring, but you can't define "id" twice. 我可以通过解构找出第二个,但是不能两次定义“ id”。 Any guidance would be much appreciated! 任何指导将不胜感激!
It seems to work if I define earlier in the component, 如果我在组件的前面定义,这似乎可行,
const firstId = (first ? first.id : '');
and replace firstId: first.id
with firstId: firstId
. 并将firstId: first.id
替换为firstId: firstId
。
If this isn't a recommended solution, please let me know! 如果这不是推荐的解决方案,请告诉我! However, it does resolve the error I was seeing and it doesn't seem to impact functionality at all. 但是,它确实解决了我所看到的错误,并且似乎根本没有影响功能。
The type checker is unable to determine if first
will ever be non null
. 类型检查器无法确定first
是否为非null
。 You can add a non-null assertion operator !
您可以添加非null断言运算符 !
directly after the object in question to tell the linter that it will not be null, try this: 直接在有问题的对象之后告诉linter,该对象将不会为null,请尝试以下操作:
{ firstId: first!.id , secondId: id }, <<<<<<
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.