ค้นหาเว็บไซต์

typescript - ฉันจะแก้ไขข้อผิดพลาด `Property 'id' does not exist on type 'Record'.` ได้อย่างไร


ฉันกำลังพยายามที่จะดึง id จากพารามิเตอร์เส้นทางใน Vuejs ฉันได้รับข้อผิดพลาดด้านล่างและไม่สามารถหาวิธีแก้ไขได้

// how I am accessing the id
const route = useRoute()
const id = route.params.id

ข้อผิดพลาดของ Typescript:

Property 'id' does not exist on type 'Record<never, never> | { all?: string[] | undefined; } | { id: string; } | { id: string; } | { id: string; }'.
  Property 'id' does not exist on type 'Record<never, never>'.ts(2339)

สิ่งที่ฉันได้ลองทำ:

ฉันได้ลองใช้ optional chaining และเข้าถึง id เป็น route.params['id'] แต่ไม่สามารถยกเลิกข้อผิดพลาดได้

ฉันสามารถแก้ไขปัญหานี้ได้อย่างไร

คำตอบ #1

let id = someDefaultValue // in case params doesn't contain id property
if("id" in route.params) id = route.params.id;

คำตอบ #2

useRoute composable รับพารามิเตอร์ _name แบบไม่จำเป็นซึ่งสามารถใช้ในการระบุเส้นทางปัจจุบันและประเภทของพารามิเตอร์ได้อย่างถูกต้อง

// if using regular router.js with named route
const route = useRoute("yourRouteNameAsDefinedInRouter");

// may also works with the path if name is not defined on the route (not tested)
const route = useRoute("/path/to/your/file/:id");

// or use file name if using unplugin-vue-router
const route = useRoute("/path/to/your/file.[id]");

// tadam! no longer throw error (and completion works)
const id = route.params.id;