Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Argument of type 'string | undefined' is not assignable to parameter of type 'string'

I have list of nestet array list, I am trying fiter based on the array value. When I filter getting error. I am using typescript with eslint.

Argument of type 'string | undefined' is not assignable to parameter of type 'string'

But I checked the null/undefined value but still I am getting error.

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"});

When I use the non-null assertion operator it the error resolved but getting lint issue.

const filterData = arrayData.filter(list => list.includes(user.username!));

Can anyone please help me to fix this issue.

like image 482
RSKMR Avatar asked Oct 20 '25 14:10

RSKMR


2 Answers

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)

like image 132
Zac Avatar answered Oct 22 '25 06:10

Zac


You can declare username like this:

username?: string | undefined;

like image 21
Timothy Alexis Vass Avatar answered Oct 22 '25 06:10

Timothy Alexis Vass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!