Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

阅读时长 2 分钟读完

As the error says, localStorage.getItem() can return either a string or null. JSON.parse() requires a string, so you should test the result of localStorage.getItem() before you try to use it.

For example:

or perhaps:

See also the answer from Willem De Nys. If you are confident that the localStorage.getItem() call can never return null you can use the non-null assertion operator to tell typescript that you know what you are doing:

来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/605420c3a33450508bd105f9

纠错
反馈