首页 > 解决方案 > 打字稿:'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!));

谁能帮我解决这个问题。

标签: javascripttypescripteslint

解决方案


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)


推荐阅读