简体   繁体   English

类型“null”不能分配给类型“string”。 角/打字稿

[英]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:所以你需要调试令牌并检查是否:

  • is not null nor undefined不是 null 也不是未定义的
  • is a string是一个字符串

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.

相关问题 我想在 Angular 中添加局部变量,但出现错误“type 'string null' is not assignable to type 'string'. typescript” - I want to add local variable in Angular but error occur "type 'string null' is not assignable to type 'string'. typescript" &#39;string | 类型的参数 null&#39; 不能分配给类型为 &#39;string&#39; 的参数。 类型 &#39;null&#39; 不能分配给类型 &#39;string&#39;。 角 12 - Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. Angular 12 键入'{类型代码:字符串; }[]' 不能分配给类型 'string[]'。 // Angular 9.1.15, TypeScript - Type '{ typecode: string; }[]' is not assignable to type 'string[]'. // Angular 9.1.15, TypeScript 当使用 Angular @Input 装饰器时,Typescript Type 'string' is not assignable to type - When using Angular @Input decorator, Typescript Type 'string' is not assignable to type 如何在 angular 中解决 - 输入 'string | null' 不可分配给类型 'string' - How to solve in angular - type 'string | null' is not assignable to type 'string' 角度打字稿错误:“字符串”类型无法分配给“任何[]”类型 - Angular typescript error: Type 'string' is not assignable to type 'any[]' 类型“事件”不可分配给类型“字符串”。 angular typescript 错误 - Type 'Event' is not assignable to type 'string'. angular typescript error 类型 'null' 不能分配给类型 'string' - Type 'null' is not assignable to type 'string' 打字稿/角度:Object 不可分配给类型 - Typescript/Angular: Object is not Assignable to type Angular - 错误 TS2322:类型 'null' 不可分配给类型 'string' - Angular - error TS2322: Type 'null' is not assignable to type 'string'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM