Typescript: Wrong error : Object is possibly 'undefined'. (TS2532)

Created on 14 Nov 2020  路  1Comment  路  Source: microsoft/TypeScript


TypeScript Version: v4.2.0-dev.20201112


Search Terms: TS2532, undefined

Code

export default function App() {
  const { data, error } = useSWR<object, Error>(
    "https://jsonblob.com/api/jsonBlob/01861067-2595-11eb-bacf-717e52210c0a"
  );

  if (!data && !error) {
    return <div>Loading...</div>;
  } else if (error) {
    return <div>Error: {error.message}</div>;
  }

  return <div>{data.array}</div>;
}

Expected behavior: There is no way data can be undefined when it's rendered

Actual behavior: Object is possibly 'undefined'. (TS2532) appears at data.array

Playground Link: https://codesandbox.io/s/object-is-possibly-undefined-ts2532-n3kxp

Related Issues: I already searched but no result for me.

Design Limitation

Most helpful comment

We don't have any mechanisms in place that can account for the complementarity of x and !x and don't plan to add any. There's no reason not to write this code more straightforwardly:

if (data) {
  return data.array;
}
if (error) {
  return "error";
}
return "loading";

>All comments

We don't have any mechanisms in place that can account for the complementarity of x and !x and don't plan to add any. There's no reason not to write this code more straightforwardly:

if (data) {
  return data.array;
}
if (error) {
  return "error";
}
return "loading";
Was this page helpful?
0 / 5 - 0 ratings