'Declaring object's key type in react typescript
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
Solution 1:[1]
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];
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bas bas |
| Solution 2 | Damian Green |
