I have an error message:
Type 'null' is not assignable to type 'string'.
Edit 2022-02-02
CodePudding user response:
This is just the typescript compiler telling you that token may be null. So you need to check that it isn't before using it in the decode function, since decode does not accept a null parameter.
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
if (token) const { userName, roleId } = decode(token);
console.log(roleId);
You can also force the typescript compiler to ignore this using !, which says "this variable will be truthy, trust me", but you need to be absolutely sure it will never be null, or you may get a runtime error.
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
const { userName, roleId } = decode(token!);
console.log(roleId);
CodePudding user response:
Thinking like typescript thinks, you need to define a type (i.e. "string", "number", "void") for variables as well as functions or methods.
Ones you have defined type for variables (or for methods), typescript check if its type match with its definition.
In your case token is probably null and typescript alert you that string not match with null and rise an error.
So you need to debug token and check if:
- is not null nor undefined
- is a string
In some cases you need to declare type of variable in the following way:
token: string = ...



