无法在打字稿上正确定义函数返回类型

时间:2021-06-12 12:53:58

标签: typescript typescript-typings

这是我在 jsonwebtoken 的帮助下为解码令牌而实现的函数,我为该函数定义的返回类型存在问题,


import jwt, { decode } from "jsonwebtoken";

export const authentication = (
  token: string
): {
  error: { [message: string]: Error } | null;
  token: { [adminID: string]: string } | null | string;
} => {
  const decodedToken = jwt.decode(token);
  return {
    error: decodedToken
      ? null
      : {
          message: new Error("invalid error"),
        },
    token: decodedToken ? decodedToken : null,
  };
};

我正在尝试使用像下面的代码片段一样的功能

  const { token, error } = authentication(context.headers.authorization);
  if (error) {
    throw new Error(error.message.toString());
  }

  const { adminID } = token;
  console.log("this is admin id", adminID);

在这部分中,当我要通过对象解构类型脚本获取 adminID 时,会像这样抛出错误

 Property 'adminID' does not exist on type 'string | { [adminID: string]: string; } | null'.

15   const { adminID } = token;

我需要提到一切正常,我可以从 adminID 获取 token,但是 typescript 对此负责。 任何想法将不胜感激。

1 个答案:

答案 0 :(得分:1)

{ [adminID: string]: string } 是一个 index signature:它表示可以用任何字符串索引的对象(字符串参数的名称是 adminID)并返回一个字符串。对于具有 adminID 类型的 string 属性的对象,您需要使用 { adminID: string }(可能还有 error: { message: Error } | null)。

更好的是,使用 discriminated (or tagged) union 而不是两个字段,其中一个必须为空。大概是这样的:

export const authentication = (
  token: string
): { kind: "error", error: Error } | { kind: "token", adminId: string }
  const decodedToken = jwt.decode(token);
  return decodedToken
      ? { kind: "token", ...decodedToken }
      : { kind: "error", error: new Error("invalid error") };
};

当然,使用它的代码也需要更改:

const authResult = authentication(context.headers.authorization);
if (authResult.kind === "error") {
  throw new Error(authResult.error.toString());
}

const { adminID } = authResult.token;
console.log("this is admin id", adminID);
相关问题