当我进行隐式检查时,Typescript抱怨输入为空
我的代码中有这么简单的东西当我进行隐式检查时,Typescript抱怨输入为空,typescript,Typescript,我的代码中有这么简单的东西 const baseAntcsStorageKey = 'abv' const userId:string= localStorage.getItem(baseAntcsStorageKey) ? localStorage.getItem(baseAntcsStorageKey) : "missing_userId" 但是typescript一直给我以下错误 类型“string | null”不可分配给类型“string”。键入“null” 不可分配给类型“s
const baseAntcsStorageKey = 'abv'
const userId:string= localStorage.getItem(baseAntcsStorageKey) ? localStorage.getItem(baseAntcsStorageKey) : "missing_userId"
但是typescript一直给我以下错误
类型“string | null”不可分配给类型“string”。键入“null”
不可分配给类型“string”
当我检查值是否不存在时,分配一个空字符串
有人能告诉我这里做错了什么吗?当Typescript看到一个getItem调用时,它会理解它将返回null或字符串。它不会将调用记忆到其类型检查器中-无论何时调用getItem,即使使用相同的参数,Typescript都会假定返回值为string | null
如果存储中的物品始终真实,请使用| |代替:
如果该项可能存在,但为空字符串,则另一个选项是首先将getItem结果保存在变量中:
const storageItem = localStorage.getItem(baseAntcsStorageKey);
const userId: string = storageItem === null ? "missing_userId" : storageItem;
通常,不能为函数的同一调用假定相同的返回值,因为不能保证函数是纯函数。对于返回字符串| null但每次不返回相同值的示例函数,请考虑:
let flag = false;
const getItem = () => {
flag = !flag;
return flag ? 'foo' : null;
};
在这里,如果使用一个参数调用一次getItem,如果使用同一个参数再次调用它,它将返回不同的结果,Typescript无法知道任意函数是否具有这种不纯属性。您的错误表明userid的类型为string或null,它与仅为string类型的localstoragegetItem不兼容
您可以将userId的类型更改为string | null
const userId:string|null = localStorage.getItem(baseAntcsStorageKey) ? localStorage.getItem(baseAntcsStorageKey) : "missing_userId"
比我的答案更好,因为我的答案会通过允许userId为null值来传播未定义的行为。
const userId:string|null = localStorage.getItem(baseAntcsStorageKey) ? localStorage.getItem(baseAntcsStorageKey) : "missing_userId"