โทเค็นเว็บ JSON - ปัญหาการคอมไพล์ jsonwebtoken ใน Typescript?
ฉันกำลังพยายามคอมไพล์ไฟล์ TypeScript และมันก็ยังคงแสดงข้อผิดพลาดนี้จากคอมไพเลอร์: error TS2339: Property 'payload' ไม่มีอยู่บนประเภท 'string | object'. Property 'payload' ไม่มีอยู่บนประเภท 'string'.
โค้ดที่กำลังสอบถาม:
decode(token: string): any {
const decodedJWT = jwt.decode(token, { complete: true });
const issuer = decodedJWT.payload.iss;
^^^^^^^^^
return {};
}
ฉันกำลังใช้ไลบรารี @types/jsonwebtoken เพื่อกำหนดประเภทใด ๆ ความช่วยเหลือใด ๆ จะได้รับการชื่นชมอย่างมาก
คำตอบ #1
ข้อผิดพลาดนี้เกิดจากการตรวจสอบประเภทของ TypeScript, ประเภทการคืนค่าของ jwt.decode() คือ null | object | string, หากคุณมั่นใจว่า jwt.decode() จะคืนค่าเป็น object เสมอ, คุณสามารถแปลง decodedJWT เป็นประเภท any เพื่อหลีกเลี่ยงข้อผิดพลาดนี้:
decode(token: string): any {
const decodedJWT = jwt.decode(token, { complete: true });
const issuer = (decodedJWT as any).payload.iss;
return {};
}
ในตัวอย่างข้างต้น อาจทำให้เกิดข้อยกเว้นในขณะรันไทม์ได้ เพราะ jwt.decode() อาจส่งค่ากลับเป็น null หรือสตริง แต่มีเพียง object เท่านั้นที่มีคุณสมบัติ payload ดังนั้นคุณควรจัดการค่าที่ส่งกลับให้อย่างปลอดภัยมากขึ้น:
decode(token: string): any {
const decodedJWT = jwt.decode(token, { complete: true });
if (decodedJWT === null) {
// deal with null
} else if (typeof decodedJWT === 'string') {
// deal with string
} else {
const issuer = (decodedJWT as any).payload.iss; // cast to `any` type
}
return {};
}
