[英]can't define function return type properly on typescript
This is the function that I have implemented for decoding the token with the aid of jsonwebtoken there is problem with return type that I have defined for the function,这是我为借助 jsonwebtoken 解码令牌而实现的 function 我为 function 定义的返回类型存在问题,
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,
};
};
I'm trying to utilize the function like the code snippet below我正在尝试像下面的代码片段一样使用 function
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);
In this part when I'm going to get adminID by object destructuring type script throws an error in like this在这部分中,当我要通过 object 获取 adminID 时,解构类型脚本会像这样抛出错误
Property 'adminID' does not exist on type 'string | { [adminID: string]: string; } | null'.
15 const { adminID } = token;
I need to mention that everything is working properly and I can get the adminID
from token
but typescript is blaming about this.我需要提一下,一切正常,我可以从
token
中获取adminID
,但 typescript 对此负责。 any idea would be appreciated.任何想法将不胜感激。
{ [adminID: string]: string }
is an index signature : it means an object that can be indexed with any string (and the name for the string parameter is adminID
) and return a string. { [adminID: string]: string }
是一个索引签名:它表示一个 object 可以用任何字符串进行索引(并且字符串参数的名称是adminID
)并返回一个字符串。 For an object with an adminID
property of type string
you want { adminID: string }
instead (and probably error: { message: Error } | null
as well).对于具有
string
类型的adminID
属性的 object,您需要{ adminID: string }
代替(并且可能error: { message: Error } | null
也是如此)。
And even better, use a discriminated (or tagged) union instead of two fields one of which must be null.甚至更好的是,使用区分(或标记)联合而不是两个字段,其中一个字段必须是 null。 Approximately like this:
大概是这样的:
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") };
};
Of course code consuming it will need to be changed as well:当然,使用它的代码也需要更改:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.