温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用typescript编写一个微信小程序项目

发布时间:2021-01-29 14:55:13 来源:亿速云 阅读:484 作者:Leah 栏目:开发技术

如何使用typescript编写一个微信小程序项目?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

{  "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 配置项

{  "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 文件,

// IAppOption.ts export default interface IAppOption {  globalData: {   text: string;  } } // app.ts import IAppOption from "./interface/IAppOption"; App<IAppOption>({  globalData: {   text: "Hello,Word!"  },  onLaunch() {  } })

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

使用 Promise 化的微信小程序api

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

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

PromisifySuccessResult 返回了Promise

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都支持

 wx.getStorageInfo({  success: () => {   console.log('成功执行')  },  fail: () => {   console.log('失败执行')  },  complete: () => {   console.log('接口调用结束')  } }) wx.getStorageInfo().then(() => {  console.log('成功执行') }).catch(() => {  console.log('失败执行') }).finally(() => {  console.log('接口调用结束') })

关于如何使用typescript编写一个微信小程序项目问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI