简体   繁体   English

用 Typescript 解构 object

[英]Destructuring object with Typescript

I have the following code however it gives me error.我有以下代码,但是它给了我错误。 I'm not sure what's the correct way to do this.我不确定这样做的正确方法是什么。 The error says错误说

Type 'CookieSessionObject | null | undefined' is not assignable to type '{ token: string; refreshToken: string; }'.
  Type 'undefined' is not assignable to type '{ token: string; refreshToken: string; }'
...
  namespace CookieSessionInterfaces {
    interface CookieSessionObject {
      token?: string;
      refreshToken?: string;
    }
  }
}

const currentUser = async (req: Request, res: Response, next: NextFunction) => {
  const { token, refreshToken }: { token: string, refreshToken: string } = req.session;
...

Also req.session?.token and req.session?.refreshToken work.还有req.session?.tokenreq.session?.refreshToken工作。

req.session can be null or undefined . req.session可以是nullundefined Hence in your case, you can handle it as:因此,在您的情况下,您可以将其处理为:

type Tokens  = {
    token?: string, 
    refreshToken?: string
}

const { token, refreshToken }: Tokens = req.session || {token: null, refreshToken: null}

else, if session is undefined or null , you can throw an exception which you can catch later and handle accordingly.否则,如果session undefinednull ,您可以throw一个异常,您可以稍后捕获并相应地处理。

if (!req.session) {
    throw new UnauthorizeException()
}

const { token, refreshToken }: Tokens = req.session

UnauthorizeException could be your custom exception or you can use some generic exception as well. UnauthorizeException可以是您的自定义异常,或者您也可以使用一些通用异常。

If you are implementing callback, you have to call callback instead of throwing exception.如果要实现回调,则必须调用回调而不是抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM