Home > Software engineering >  Best way to create empty json for typescript, or should I init with null?
Best way to create empty json for typescript, or should I init with null?

Time:08-31

Pretty simple question that I already have a solution for but it looks ugly to me.

I am trying to access local storage but I need to useEffect and if I want to extract the value from inside useEffect I need to instantiate before the codeblock in the higher scope.

Typescript does not accept var temp:JSON = {} So I have to do the cumbersome var temp:JSON = JSON.parse(JSON.stringify({})) which works. But it seems somewhat stupid to me that Javascript will randomly coerce my string into truthy values with == but can't coerce an empty Object into JSON.

CodePudding user response:

You can make it work like this:

const temp:JSON = {} as JSON;

However, you should consider why TypeScript returns an error:

error TS2739: Type '{}' is missing the following properties from type 'JSON': parse, stringify, [Symbol.toStringTag]

The type JSON is meant for the built-in JSON object and not for its output. In your case, temp is just a regular Object.

CodePudding user response:

JSON type is probably not what you need to be using for this. This type reflects an interface for converting data to/from JSON, aka the JSON global object in JavaScript.

Instead, you should create an interface that reflects the type of data stored in localstorage, then use that interface as the type for the parsed string from localstorage:

interface StoredObject {
  name?: string;
  kind?: string;
  ...
}

...

const [storedObject, setStoredObject] = useState<StoredObject>();

useEffect(() => {
  const jsonString = localStorage.getItem(key);
  setStoredObject(JSON.parse(jsonString));
}, []);

CodePudding user response:

you can do like this:

let foo:JSON = {} as JSON;

I hope it help you.

  • Related