javascript - 打字稿:'string | 类型的参数 undefined' 不能分配给“string”类型的参数
问题描述
我有嵌套数组列表的列表,我正在尝试基于数组值的 fiter。当我过滤得到错误时。我正在使用带有 eslint 的打字稿。
Argument of type 'string | undefined' is not assignable to parameter of type 'string'
但是我检查了 null/undefined 值,但仍然出现错误。
interface User {
id: string;
username?: string;
}
function getList (user:User){
if(user.username === undefined){
return {};
}
let arrayData: string[][] = [];
arrayData = [["abcd"],["efgh"],["xyz"],["abcd","xyz"]];
//here i have differnt logic
const filterData = arrayData.filter(list => list.includes(user.username));
return filterData;
}
getList({id: "123", username: "xyz"});
当我使用non-null assertion operator
它时,错误已解决,但出现 lint 问题。
const filterData = arrayData.filter(list => list.includes(user.username!));
谁能帮我解决这个问题。
解决方案
you are comparing the User .username
, which is Optional, that means it's of type string | undefined
to every string
item in an array,
you can change the type of your array to: arrayData: Array<Array<string|undefined>>
or you can just use as
to treat it as a string
, not string|undefined
: i.e.: list.includes(user.username as string)
推荐阅读
- c# - Blazored Typeahead 加载时设置值
- ios - 循环 AnyHashable 字典
- python - Python 和 Excel 公式
- java - Apache Avro Parquet java.lang.NoSuchFieldError: NULL_VALUE
- c# - c#无法将文本附加到现有文件
- c++ - 在OpenCV中将二维码投影到摄像头时,出现错误
- java - 与 JIB Gradle 集成导致编译错误
- reactjs - 如何将 pdf 文件/blob 上传到 S3?
- html - 如何在表格中的悬停元素上实现水平和垂直悬停效果:如何创建相交悬停?
- java - 将 $addToSet 与 Spring Batch MongoItemWriter 一起使用