TypeScript-未定义类型不能分配给ICustomType类型

问题描述 投票:0回答:1

我对TypeScript还是很陌生,试图了解在我的代码中解决这种情况的最佳方法是什么。

我的系统中具有自定义类型的对象数组,并且我使用Array.find方法来获取其中之一。但是,我收到一个编译错误,提示Type 'undefined' is not assignable to type IConfig

这是代码示例-

const config: IConfig = CONFIGS.find(({ code }) => code === 'default');
// Type 'undefined' is not assignable to type IConfig

我试图将undefined添加为可能的类型,但随后在使用此对象Object is possibly 'undefined'的下一行出现错误,例如-

const config: IConfig | undefined = CONFIGS.find(({ code }) => code === 'default');

// Object is possibly 'undefined'
if (config.foo) {
   return 'bar';
}

解决此类类型问题的最佳方法是什么?

node.js typescript types
1个回答
1
投票
如果数组中的任何内容均未通过回调测试,则

.find将返回undefined。如果确定数组中存在default代码,请使用非null断言运算符:

const config: IConfig = CONFIGS.find(({ code }) => code === 'default')!;
//                                                                    ^

((如果不确定数组中是否存在该警告,则会出现警告,提示您在尝试访问该属性之前会明确测试该项目是否存在,否则有时会获得运行时错误:

const config: IConfig = CONFIGS.find(({ code }) => code === 'default');

if (!config) {
  return 'No match found';
}
if (config.foo) {
   return 'bar';
}

© www.soinside.com 2019 - 2024. All rights reserved.