typescript - Bagaimana saya bisa menyelesaikan `Property 'id' does not exist on type 'Record'.`
Saya sedang mencoba mendapatkan id dari param rute di Vuejs. Saya mendapatkan kesalahan di bawah ini dan tidak bisa menemukan cara untuk menyelesaikannya.
// how I am accessing the id
const route = useRoute()
const id = route.params.id
Kesalahan 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)
Apa yang telah saya coba:
Saya telah mencoba menggunakan optional chaining dan mengakses id sebagai route.params['id'] tetapi tidak bisa menekan error tersebut.
Bagaimana saya bisa menyelesaikan masalah ini.
Jawaban #1
let id = someDefaultValue // in case params doesn't contain id property
if("id" in route.params) id = route.params.id;
Jawaban #2
Composable useRoute menerima parameter opsional _name yang bisa digunakan untuk menafsirkan rute saat ini dan tipe parameter dengan benar.
// 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;
