[英]Type 'null' is not assignable to type 'string'. Angular/TypeScript
I have an error message:我有一条错误消息:
Type 'null' is not assignable to type 'string'.
I found a solution here but I didn't understand the answers for my problem.我在这里找到了解决方案,但我不明白我的问题的答案。
My code is presented like this:我的代码如下所示:
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
const { userName, roleId } = decode(token);
console.log(roleId);
Edit 2022-02-02编辑 2022-02-02
decode method解码方法
export class InvalidTokenError extends Error {}
export interface JwtDecodeOptions {
header?: boolean;
}
export interface JwtHeader {
type?: string;
alg?: string;
}
export interface JwtPayload {
iss?: string;
sub?: string;
aud?: string[] | string;
exp?: number;
nbf?: number;
iat?: number;
jti?: string;
}
export default function jwtDecode<T = unknown>(
token: string,
options?: JwtDecodeOptions
): T;
FYI, I copied the code from the project here仅供参考,我从这里的项目中复制了代码
This is just the typescript compiler telling you that token
may be null
.这只是 typescript 编译器告诉您token
可能是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.所以你需要在decode
function 之前检查它是否不是,因为decode
不接受null
参数。
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 !
您还可以强制 typescript 编译器使用!
, 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. ,上面写着“这个变量是真实的,相信我”,但你需要绝对确定它永远不会是null
,否则你可能会遇到运行时错误。
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
const { userName, roleId } = decode(token!);
console.log(roleId);
Edit编辑
This solution should work regardless, but you should define the correct return types for decode无论如何,此解决方案都应该有效,但是您应该为解码定义正确的返回类型
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
if (token) const info: { userName, roleId } = decode(token);
console.log(info.roleId);
OR或者
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
if (token) const info: any = decode(token);
console.log(info.roleId);
Edit 2编辑 2
Looks like decode
is a generic function, so you can define the return type like this:看起来decode
是一个通用的 function,所以你可以像这样定义返回类型:
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
if (token) const { userName, roleId } = decode<{ userName, roleId }>(token);
console.log(roleId);
Thinking like typescript thinks, you need to define a type (ie "string", "number", "void") for variables as well as functions or methods.像 typescript 那样思考,您需要为变量以及函数或方法定义一个类型(即“字符串”、“数字”、“无效”)。
Ones you have defined type for variables (or for methods), typescript check if its type match with its definition.您为变量(或方法)定义类型的那些,typescript 检查其类型是否与其定义匹配。
In your case token
is probably null and typescript alert you that string not match with null and rise an error.在您的情况下, token
可能是null和 typescript 提醒您该字符串与null不匹配并引发错误。
So you need to debug token and check if:所以你需要调试令牌并检查是否:
In some cases you need to declare type of variable in the following way:在某些情况下,您需要通过以下方式声明变量类型:
token: string =...
I was able to fix the problem by modifying this:我能够通过修改这个来解决这个问题:
export class RoleGuard implements CanActivate {
constructor(
private authService: AuthService,
public router: Router
){ }
canActivate(route: ActivatedRouteSnapshot):boolean{
const expectedRole = route.data.expectedRole;
const token = localStorage.getItem('token');
const { userName, roleId } = decode(token);
console.log(roleId);
if( !this.authService.isAuth() || roleId !== expectedRole){
console.log('Usuario no autorizado para la vista');
this.router.navigate(['login']);
return false;
}
return true;
}
}
To this:对此:
export class RoleGuard implements CanActivate {
constructor(
private authService: AuthService,
public router: Router
) { }
canActivate(route: ActivatedRouteSnapshot): boolean {
const expectedRole = route.data['expectedRole'];
const token = localStorage.getItem('token');
if (!this.authService.isAuth()) {
console.log('Usuario no autorizado para la vista');
this.router.navigate(['login']);
};
const info: { userName: string, roleId: string } = decode(token);
if (info.roleId != expectedRole) {
console.log('Usuario no autorizado para la vista');
this.router.navigate(['login']);
return false;
}
return true;
} } } }
I separated the if into 2 if, each one performing an independent activity我将 if 分成 2 个 if,每个 if 执行一个独立的活动
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.