uniappx语法差异汇总(附详细示例)
作者:darly
uni-app x是下一代uni-app,一个神奇的产品,用vue语法、uni的组件、api,以及uts语言,编译出了kotlin的app,这篇文章主要介绍了uniappx语法差异的相关资料,需要的朋友可以参考下
前言
最近在做一个uniappx开发Android、iOS、微信小程序的项目,开发过程中遇到很多报错。其中语法报错占据大多数,下面是语法报错解决之后的汇总
- 所有变量都要声明类型;
- 对象的类型声明不能嵌套,原因未知;
- 部分 JS 语法不支持;
- 不同平台对编写语法要求不同,所以调试时应该同时运行Android和iOS及时发现报错。
不支持的 JS/TS 语法
// 1.解构
const { a, b } = response.data; // 不支持
const data = {...response.data, ...other} // 不支持
// 2.对象的变量取值
const a = "a";
const obj = {
a() {
return "test";
},
};
obj[a](); // 不支持
// 3. 函数返回Promise时同时有resolve和reject会有类型推断问题。
const promiseExample = (param: booleam) => { // 会报错,暂未找到解决办法,只能全部使用Promise.reslove
if(param) {
return Promise.reslove("")
} else {
return Promise.reject(new Error())
}
}
// 4. 不支持短路操作
const str = other || "get" //错误用法,str在APP上为 false
let str: string; // 正确用法:显式的为变量赋值
if(typeof other === "string") {
str === other
} else {
str === "get"
}
// 5. 没有隐式类型转换
const a = ""
if(a) { // 错误用法,会报类型错误
// handles
}
if(typeof a === "string") { // 正确用法1
// handles
}
if(a === "") {// 正确用法2
// handles
}
// 6. 对象未定义属性值引用
const config = {
a: "a"
}
fun(config.g) // Unresolved reference: g
// 7. 为对象的可选属性的属性赋值
interface MyObject {
optionalProp?: {
nestedProp: string;
};
}
const obj: MyObject = {
// ...
}
// 为可选属性的属性赋值包含两步,分别是逻辑判断是否为空和类型断言
if (typeof obj.optionalProp === "object") {
obj.optionalProp!.nestedProp = "1234"
}
// 8. Promise.all()的返回值不能确定类型,所以要显式的处理一次
Promise.all(dataList.map(handles as Promise<string>))// 返回类型为Promise<unknow[]>,需要在.then的成功回调里return类型明确的值
.then((res : string[]) => res.join(","))
总结
到此这篇关于uniappx语法差异汇总的文章就介绍到这了,更多相关uniappx语法差异内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
