[英]Typescript: can't define return type of a function from multiple conditional typings
[英]can't define function return type properly on typescript
这是我为借助 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,
};
};
我正在尝试像下面的代码片段一样使用 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);
在这部分中,当我要通过 object 获取 adminID 时,解构类型脚本会像这样抛出错误
Property 'adminID' does not exist on type 'string | { [adminID: string]: string; } | null'.
15 const { adminID } = token;
我需要提一下,一切正常,我可以从token
中获取adminID
,但 typescript 对此负责。 任何想法将不胜感激。
{ [adminID: string]: string }
是一个索引签名:它表示一个 object 可以用任何字符串进行索引(并且字符串参数的名称是adminID
)并返回一个字符串。 对于具有string
类型的adminID
属性的 object,您需要{ adminID: string }
代替(并且可能error: { message: Error } | null
也是如此)。
甚至更好的是,使用区分(或标记)联合而不是两个字段,其中一个字段必须是 null。 大概是这样的:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.