Vue+TypeScript报错:类型'Users[]'缺少ArrayConstructor相关属性
Vue+TypeScript类型错误解决:Type 'Users[]'缺失ArrayConstructor属性
错误信息
Type 'Users[]' is missing the following properties from type 'ArrayConstructor': isArray, prototype, from, of, [Symbol.species]
问题代码
GetAll.controller.ts
import { supabase } from "../server"; type Users = { user_id: Number, user_username: String, user_email: String, user_password: String, user_token: String } export async function GetAll():Promise<Users[]> { console.log('go'); try { let { data, error } = await supabase .from('users') .select('*') if (error) throw error if (data) { return data } else { throw data } } catch (err) { throw(err); } }
App.vue
<script lang="ts"> import {GetAll} from './API/GetAll.controller'; export default { name: 'app', data(){ return { users: Array } }, async mounted() { this.users = await GetAll() } } </script>
问题原因
你在data里把users初始化为Array(数组构造函数),TypeScript因此推断users的类型是ArrayConstructor,但GetAll()返回的是Users[](数组实例),两种类型完全不匹配,导致类型校验失败。
解决方案
把users的初始值改为空数组,同时可以明确标注类型让代码更严谨:
修改后的App.vue:
<script lang="ts"> import {GetAll, Users} from './API/GetAll.controller'; // 导入Users类型 export default { name: 'app', data(){ return { users: [] as Users[] // 初始化为空数组,并用类型断言指定为Users[] } }, async mounted() { this.users = await GetAll() } } </script>
额外优化建议
- 类型定义里的
Number/String要改成小写的number/string,大写的是构造函数类型,基本类型应该用小写:
type Users = { user_id: number, user_username: string, user_email: string, user_password: string, user_token: string }
GetAll函数里可以简化错误处理,避免多余的throw data:
export async function GetAll():Promise<Users[]> { console.log('go'); const { data, error } = await supabase.from('users').select('*') if (error) throw error return data || [] // 数据为空时返回空数组,避免抛出无意义的错误 }
内容的提问来源于stack exchange,提问作者ambroiselebs
相关产品推荐
相关产品推荐

