JS类型提示

1 xxx.d.ts 声明文件

解决在ts文件中使用js文件没有类型声明的问题

1.1 Common.js 模块类型声明文件

  • 目录结构

    • src
      • test
        • test.js
        • test.d.ts
      • common.js
    • jsconfig.json
  • 函数文件声明

// test.js

// commonjs 导出一个模块
module.exports = {
    getUser: (id) => ({id,message:'test success'})
}

// 导出单个function
// module.export = (id) => ({id,message:'test success'})
  • 类型文件声明
// test.d.ts
declare function getUser(id: number): { id: number; name: string }

// 导出模块声明
export = {
  getUser
}

// 导出单个声明
// export = getUser
  • 使用
// common.js
const User = require('./test/test')

// 结构形式
// const { getUser } = require('./test/test')

user.getUser(1) // { id: 1, message: 'test success' }
// getUser(1)   // { id: 1, message: 'test success' }
  • 类型提示
  • ts文件中使用js文件,解决没有类型声明问题

1.2 ES6 模块类型声明文件

目录结构

  • src

    • test
      • test.js
      • test.d.ts
    • common.js
  • jsconfig.json

  • 函数文件声明

// test.js

// es6 默认导出一个对象
export default = {
   test: (id) => ({id,message:'test success'})
}


// es6 默认导出单个
// export default function test(id){
//    return {
//        id,
//        message: 'test success'
//    }
// }


// 导出单个function
// export function test(id){
//    return { id, message: 'test success' }
// }

// 接收 结构形式
// import { test } from './test/tets'

// 接收 将内部所有的单个导出 as 作为一个对象
// import * as Test from './test/test'
  • 类型文件声明
// test.d.ts
declare function test(id: number): { id: number; name: string }

// 导出模块声明
export {
  test
}

// 导出单个声明
// export test
  • 使用
// common.js
const Test = require('./test/test')

Test.test(1) // { id: 1, message: 'test success' }
  • 类型提示

2.jsdoc 类型注解

  • 直接书写
/**
 * 获取用户信息
 *
 * @param {number} id
 * @return {{id: number, message: string}}
 */
function getUser(id) {
  return {
    id,
    message: 'test success'
  }
}
  • 类型提示

3. 给类型文件添加注释

  • ES6模块声明文件为例
/**
 * 测试
 *
 * @param {*} id
 * @return {*}  {{ id: number; message: string }}
 */
declare function test(id: number): { id: number; message: string }
export { test }
  • 类型提示
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值