我觉得很奇怪。在lib.dom.d.ts中,localstorage.getItem的类型返回值是'string | null',但是在我的应用程序中使用它时,它总是返回字符串(string)。为什么呢?
getItem()
方法会返回 null
。因此,TypeScript 的注释定义了一个 string
和 null
的联合类型。 - nalplylocalStorage
中使用 json 对象,可以使用 JSON.stringify()
和 JSON.parse()
方法。localStorage.setItem('token', JSON.stringify(user));
user = JSON.parse(localStorage.getItem('user'));
在这里,您将获得对象而不是字符串。
localStorage.getItem(Math.random())
。请注意,此函数将返回一个随机生成的字符串作为键名。 - Kaiido