3

Im learning typescript and cant find out what does this mean. The error says Type 'FriendListItem[] | null' is not an array type.ts(2461). But when typing FriendList[], that means it will be array of FriendListItem items, right ?

  interface FriendListItem {
  id: number;
  name: string;
  address: string;
}

const App = () => {
  const { data, done } = useFetchAll(
    "https://jsonplaceholder.typicode.com/users"
  );
  const [friendList, setFriendList] = useState<FriendListItem[] | null>(null);

  const addToFriendList = (friend: FriendListItem): void => {
    **setFriendList((prevstate) => [...prevstate, { friend }]);**
  };

  const removeFromFriendList = (id: string) => {};

  return (
    <div className="app">
      <Layout>
        <Switch>
          <Route path="/" exact />
          <Route path="/everyone" exact>
            <Everyone data={data} done={done} />
          </Route>
          <Route path="/everyone/:userId">
            <UserDetail addToFriendList={addToFriendList} />
          </Route>
        </Switch>
      </Layout>
    </div>
  );
};

export default App;

Edit: Adding my testconfig file, which is generated from cra --template typescript, did not change anything

    {
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}
4
  • you should include your tsconfig.json file and what version of TS you are using Commented Aug 25, 2021 at 13:34
  • You are trying to apply a spread to null, e.g. [...null, { friend }]. Pass an empty array as the default value to useState Commented Aug 25, 2021 at 13:35
  • @JaredSmith just did and it still throw that error Commented Aug 25, 2021 at 13:38
  • 1
    @Daniels0n you have to change the generic type parameter too: useState<FriendListItem[]>([]); again, you can't use a spread on something that you've told the compiler might be null. Commented Aug 25, 2021 at 13:40

1 Answer 1

2

Because friendList is an array or null. So need to check before use spread operator:

  const addToFriendList = (friend: FriendListItem): void => {
    setFriendList((prevstate) => prevstate ? [...prevstate, friend] : [friend]);
  };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.