javascript - วิธีแปลงชนิดข้อมูลที่ไม่ทราบเป็นสตริงใน TypeScript?
ฉันกำลังจัดการกับอินเทอร์เฟซจากโค้ดภายนอก สรุปให้น้อยที่สุดมันดูเหมือนแบบนี้:
interface Input {
details?: unknown;
}
ตอนนี้ฉันจำเป็นต้องแมปวัตถุนี้ไปยังวัตถุอื่นที่มีประเภท:
interface Output {
message?: string;
}
ดังนั้น unknown ต้องถูกแปลงเป็น string วิธีเริ่มต้นของฉันคือการเรียก input.details.toString() แต่ toString ไม่สามารถใช้งานได้เพราะ unknown อาจเป็น null หรือ undefined ก็ได้
ฉันจะแปลง Input เป็น Output ได้อย่างไร?
คำตอบ #1
ในการแปลง unknown เป็น string คุณสามารถใช้การตรวจสอบชนิดแบบ typeof ประเภทของนิพจน์ ternary ด้านล่างจะถูกสรุปเป็น string | undefined:
const output: Output = {
message: typeof input.details === 'string'
? input.details
: undefined,
};
