自写一个函数将js对象转为Ts的Interface接口

本文介绍了一种方法,通过编写函数将JavaScript对象自动转换为TypeScript接口,减少手动定义接口的工作量,适用于提高前端开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如今的前端开发typescript
已经成为一项必不可以少的技能了,但是频繁的定义Interface接口会给我带来许多工作量,我想了想如何来减少这些非必要且费时的工作量呢,于是决定写一个函数,将对象放进它自动帮我们转换成Interface接口,接下来就是复制粘贴的工作了,当然了如果需要调整》我们可以在手动调一下,比起一个个的定义花费的时间肯定是短了很多的。我们还以自己去完善这个函数,以达到更多你想要的效果,动手能力强的小伙伴可以尝试起来了。

可以将以下代码放入ts文件中:

// 自写一个函数将js对象转为ts接口 (参数1 js对象,参数2 ts接口名)
    function generateInterface(
      obj: any,
      interfaceName: string = 'myGeneratedInterface'
    ): string {
      const getType = (value: any): string => {
        if (value === null) {
          return 'any'
        } else if (Array.isArray(value)) {
          const arrayItemType = value.length > 0 ? getType(value[0]) : 'any'
          return `${arrayItemType}[]`
        } else if (typeof value === 'object') {
          // interfaceName + 'Item'
          return generateInterface(value, '')
        } else {
          if (typeof value === 'function') {
            return 'Function'
          }
          return typeof value
        }
      }

      const properties: string[] = []

      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          const value = obj[key]
          const type = getType(value)
          properties.push(`${key}: ${type};`)
        }
      }
      // 最外层的添加 interface ${interfaceName}
      let interfaceCode
      if (interfaceName) {
        interfaceCode = `interface ${interfaceName} {
${properties.join('\n    ')}
}`
      } else {
        interfaceCode = `{
${properties.join('\n    ')}
}`
      }
      return interfaceCode
    }
    // 用该对象测试
    const myObject = {
      name: 'John',
      age: 18,
      isStudent: true,
      hobbies: ['reading', 'coding'],
      address: {
        city: 'Example City',
        zipCode: 12345,
        hobbies2: ['reading', 'coding'],
        isStudent2: true,
      },
      nullValue: null,
    }
    // 打印测试下转换的结果如何
    console.log(generateInterface(myObject, 'Person'))
    // 最终打印结果:
    // interface Person {
    //     name: string;
    //     age: number;
    //     isStudent: boolean;
    //     hobbies: string[];
    //     address: {
    //         city: string;
    //         zipCode: number;
    //         hobbies2: string[];
    //         isStudent2: boolean;
    //     };
    //     nullValue: any;
    // }

看一下控制台呈现的结果:

看起来还不错,控制台输出的这段代码复制粘贴 就可以使用了。

欢迎关注我的原创文章:小伙伴们!我是一名热衷于前端开发的作者,致力于分享我的知识和经验,帮助其他学习前端的小伙伴们。在我的文章中,你将会找到大量关于前端开发的精彩内容。

学习前端技术是现代互联网时代中非常重要的一项技能。无论你是想成为一名专业的前端工程师,还是仅仅对前端开发感兴趣,我的文章将能为你提供宝贵的指导和知识。

在我的文章中,你将会学到如何使用HTML、CSS和JavaScript创建精美的网页。我将深入讲解每个语言的基础知识,并提供一些实用技巧和最佳实践。无论你是初学者还是有一定经验的开发者,我的文章都能够满足你的学习需求。

此外,我还会分享一些关于前端开发的最新动态和行业趋势。互联网技术在不断发展,新的框架和工具层出不穷。通过我的文章,你将会了解到最新的前端技术趋势,并了解如何应对这些变化。

我深知学习前端不易,因此我将尽力以简洁明了的方式解释复杂的概念,并提供一些易于理解的实例和案例。我希望我的文章能够帮助你更快地理解前端开发,并提升你的技能。

如果你想了解更多关于前端开发的内容,不妨关注我的原创文章。我会不定期更新,为你带来最新的前端技术和知识。感谢你的关注和支持,我们一起探讨交流技术共同进步,期待与你一同探索前端开发的奇妙世界!

要在Electron + TypeScript + Vite项目中调用Everything.dll实现快速搜索,可以按照以下步骤进行操作: 1. 安装Everything软件并启动它,确保Everything.dll已经被正确安装。 2. 在项目中安装node-ffi和ref-napi,这两个模块可以帮助我们在Node.js中调用DLL函数。可以使用以下命令进行安装: ```bash npm install node-ffi ref-napi ``` 3. 创建一个名为everything.tsTypeScript模块,并在其中定义我们要调用的Everything.dll函数。可以参考以下代码: ```typescript import { FFI } from 'ffi-napi'; /** * Everything.dll中的函数声明 */ export interface EverythingDLL extends FFI.Library { Everything_SetSearchW: (search: Buffer) => void; Everything_QueryW: (wait: number) => void; Everything_GetNumResults: () => number; Everything_GetResultFullPathNameW: (index: number, buf: Buffer, size: number) => number; Everything_CleanUp: () => void; } /** * 加载Everything.dll */ const everythingDll: EverythingDLL = FFI.Library('Everything.dll', { Everything_SetSearchW: ['void', ['pointer']], Everything_QueryW: ['void', ['int']], Everything_GetNumResults: ['int', []], Everything_GetResultFullPathNameW: ['int', ['int', 'pointer', 'int']], Everything_CleanUp: ['void', []], }); export default everythingDll; ``` 4. 在项目中使用everything.ts模块来进行搜索。可以参考以下代码: ```typescript import everythingDll from './everything'; /** * 搜索文件 * @param search 搜索关键字 * @returns 搜索结果数组 */ export function searchFiles(search: string): string[] { // 将搜索关键字转为UTF-16编码的Buffer const searchBuffer = Buffer.from(search, 'ucs2'); // 设置搜索关键字 everythingDll.Everything_SetSearchW(searchBuffer); // 执行搜索 everythingDll.Everything_QueryW(1); // 获取搜索结果数量 const resultCount = everythingDll.Everything_GetNumResults(); // 获取搜索结果 const results: string[] = []; for (let i = 0; i < resultCount; i++) { const buf = Buffer.alloc(4096); everythingDll.Everything_GetResultFullPathNameW(i, buf, buf.length); const result = buf.toString('ucs2'); results.push(result); } // 清理搜索结果 everythingDll.Everything_CleanUp(); return results; } ``` 5. 在Electron应用程序中使用searchFiles函数进行搜索。可以参考以下代码: ```typescript import { app, BrowserWindow } from 'electron'; import { searchFiles } from './everything'; function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, }, }); win.loadFile('index.html'); // 在渲染进程中使用searchFiles函数进行搜索 win.webContents.on('did-finish-load', () => { const results = searchFiles('test'); console.log(results); }); } app.whenReady().then(() => { createWindow(); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); ``` 这样就可以在Electron + TypeScript + Vite项目中调用Everything.dll实现快速搜索了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值