Vuetify+Inertia+TypeScript:如何为v-autocomplete的items正确类型标注?
解决TypeScript对Inertia共享数据$page.props.countries的类型报错问题
1. 定义Country类型
先明确你的国家对象结构,创建对应的TypeScript接口:
// 可放在src/types/Country.ts或组件文件内 interface Country { id: number; name: string; // 按需添加其他属性,比如国家代码code等 }
2. 全局扩展Inertia的PageProps类型
Inertia默认的$page.props类型为unknown,需要全局扩展它的类型来包含countries属性。在项目的types目录下创建(或修改)inertia.d.ts文件:
import { PageProps } from '@inertiajs/core'; import { Country } from './Country'; // 引入刚才定义的Country类型 declare module '@inertiajs/core' { interface PageProps { countries?: Country[]; // 用可选符?适配不需要该属性的页面 } }
确保tsconfig.json已配置包含该types目录:
{ "compilerOptions": { "typeRoots": ["./node_modules/@types", "./src/types"] } }
3. 组件内类型断言(可选方案)
如果不想全局扩展,也可以在组件内直接通过类型断言指定countries的类型:
<template> <v-autocomplete :items="countries"></v-autocomplete> </template> <script setup lang="ts"> import { Country } from '@/types'; // 断言$page.props包含countries属性且为Country数组 const countries = ($page.props as { countries: Country[] }).countries; </script>
完成以上操作后,TypeScript就能正确识别countries是Country[]类型,不会再抛出Type unknown is not assignable to type readonly any[] | undefined的错误。
内容的提问来源于stack exchange,提问作者superfive33
相关产品推荐
相关产品推荐

