typescript编写微信小程序创建项目的方法

网友投稿 346 2023-11-09

创建项目

在微信开发者工具创建项目,在语言中选择 TypeScript

改造项目

typescript编写微信小程序创建项目的方法

编辑 package.json 文件,修改 miniprogram-api-typings 和 typescript 版本

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "miniprogram-ts-quickstart",
"version": "1.0.0",
"description": "",
"scripts": {
"compile": "./node_modules/typescript/bin/tsc",
"tsc": "node ./node_modules/typescript/lib/tsc.js"
},
"keywords": [],
"author": "",
"license": "",
"dependencies": {
},
"devDependencies": {
"typescript": "^4.1.3",
"miniprogram-api-typings": "^2.12.1-beta.0"
}
}

编辑 tsconfig.json 文件, 修改 lib 为 ["esnext"],支持最新语法, 删除 typeRoots 配置项

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"compilerOptions": {
"strictNullChecks": true,
"noImplicitAny": true,
"module": "CommonJS",
"target": "ES5",
"allowJs": false,
"experimentalDecorators": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"inlineSourceMap": true,
"inlineSources": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"removeComments": true,
"pretty": true,
"strictPropertyInitialization": true,
"lib": ["esnext"]
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}

执行 npm install

删除项目下 typings 目录, 的 复制 node_modules 下 miniprogram-api-typings 的 types 文件到项目根目录

在 miniprogram 下创建 interface 目录并创建 IAppOption.ts 文件,最后编辑 app.ts 文件,

在 详细 -> 本地设置 -> 调试基础库,直接选择最新的

使用 Promise 化的微信小程序api

以前可以通过 miniprogram-api-promise 这个包来完成 api Promise 化,或者自己写

现在可以直接使用,比如 wx.getStorageInfo ,在 lib.wx.api.d.ts 中返回了 PromisifySuccessResult

PromisifySuccessResult 返回了Promise

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
getStorageInfo<TOption extends GetStorageInfoOption>(
option?: TOption
): PromisifySuccessResult<TOption, GetStorageInfoOption>
type PromisifySuccessResult<
P,
T extends AsyncMethodOptionLike
> = P extends { success: any }
? void
: P extends { fail: any }
? void
: P extends { complete: any }
? void
: Promise<Parameters<Exclude<T[success], undefined>>[0]>

两种用法,大多数api都支持

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
wx.getStorageInfo({
success: () => {
console.log(成功执行)
},
fail: () => {
console.log(失败执行)
},
complete: () => {
console.log(接口调用结束)
}
})
wx.getStorageInfo().then(() => {
console.log(成功执行)
}).catch(() => {
console.log(失败执行)
}).finally(() => {
console.log(接口调用结束)
})

源码: https://github.com/NikolasSky/ts-miniprogram/tree/master/ts-miniprogram-base

到此

您可能感兴趣的文章:前端深入理解Typescript泛型概念详解JavaScript私有类字段和TypeScript私有修饰符JS装饰者模式和TypeScript装饰器详解TypeScript中的类型保护TypeScript在React项目中的使用实践总结Vue3+TypeScript封装axios并进行请求调用的实现TypeScript 安装使用及基本数据类型详解Typescript里的This的使用方法TypeScript泛型参数默认类型和新的strict编译选项

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:信创操作系统—为什么信创操作系统是您的最佳选择?
下一篇:微信小程序上线发布具体流程简析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~