刚开始学习uniappx,在封装request请求时遇到这个错误,这是什么原因呢?
error: Cannot use 'T' as reified type parameter. Use a class instead.
error: Cannot use 'U' as reified type parameter. Use a class instead.
export class Request {
protected BASE_URL = 'http://10.200.0.208/app';
private request<T, U = null>(url : string, method : 'GET' | 'POST', data : U | null, callback : (res : T) => void) : void {
uni.request<T>({
url: this.BASE_URL + url,
method: method,
data: data,
timeout: 5000,
success: (res) => {
console.log(res)
},
fail: (err) => {
console.log(err);
}
})
}
public get<T, U>(url : string, callback : (res : T) => void) : void {
this.request<T, U>(url, 'GET', null, callback);
}
}
type ApiResult<T> = {
code : number,
msg : string,
data : T
}
type Test = {
id : number,
name : string
}
type Param = {
id : number
}
http.get<ApiResult<Test>, Param>('/index/test', (res) => {
console.log(res);
})
1 个回复
Ask小助手 - Ask社区AI助手
在 uni-app x(UTS)里,
Cannot use 'T' as reified type parameter. Use a class instead.这条编译错误并不是 uni.request 本身的问题,而是 UTS 在 Android 平台对泛型的实现限制导致的。简单理解:UTS 把 TypeScript 的泛型编译到 Kotlin/Swift 时,不能把泛型参数 T 当成“运行时真实存在的类型”去用。一旦代码里把 T 当成值(例如
uni.request<T>这种写法),Android 编译器就会报这个错。官方文档里专门有一段说明:安卓平台使用泛型注意事项 —— 里面给出的解决方案就是:
这两个注解,让 Kotlin 用
inline reified方式保留泛型信息。示例(官方给出的完整写法):
使用:
这样就能在 Android 上正常通过泛型拿到强类型数据,也不会再出现
Cannot use 'T' as reified type parameter的错误。总结
uni.request<T>在 Android 端会报该错;inline reified的壳子 + 一个普通函数做实际请求;要回复问题请先登录或注册
公告
更多>相关问题