4

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.

1
  • User Interface already defined. so unable to "username?: string | undefined;" Commented Jan 24, 2021 at 8:30

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Just putting an exclamation at the end of the variable worked for me.
2

You can declare username like this:

username?: string | undefined;

1 Comment

User Interface already defined. so unable to "username?: string | undefined;"
2

when you want to set a variable that already has a type | undefined, and the setter doesn't accept any type | undefined, you could use the ! at the end of the variable for example:

for an interface like yours

interface User { id: int; username?: string }

having a variable like

let userVariable = 'Terminator3000'

you can do

user: User = { id: 123, username: userVariable! }

! operator indicates that the value isn't undefined

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.