Home > database >  Declaring object's key type in react typescript
Declaring object's key type in react typescript

Time:05-24

first time using Typescript, I'm a bit confused about how I should do this. I have and object with these keys:

interface eachUserInt {
    avatar: string;
    name: string;
    uid: string;
    friends: userInterface[];
    requests: userInterface[];
  }

The userInterface is this:

interface userInterface {
    name: string;
    avatar: string;
    uid: string;
  }

So the requests key is an object with keys name, avatar and uid, right? I'm declaring the state as:

const [eachUser, setEachUser] = useState<eachUserInt | null>(null);

Below all of it, i have this:

const friend: userInterface = eachUser?.requests[index];

But it throws the error:

Type 'userInterface | undefined' is not assignable to type 'userInterface'.
  Type 'undefined' is not assignable to type 'userInterface'

What am i missing here? Thanks in advance

CodePudding user response:

Its just as the error says

Since friend is of type userInterface and eachUser?.requests[index]; can return either undefined or userInterface it would cause that error. To fix this, you just tell typescript it could also be undefined.

const friend: userInterface | undefined = eachUser?.requests[index];

CodePudding user response:

A couple of issues

See Playground Firstly your requests property is not nullable (?.) currently. So it needs to be;

requests?: userInterface[];

Secondly, if it's nullable you'll need to do a null coalesce:

eachUser?.requests?.[index];

Otherwise you'd get a Object is possibly 'undefined'.(2532) error.

  • Related