我对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';
}
解决此类类型问题的最佳方法是什么?
.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';
}
)