You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript项目中用Prettier将Array<T>格式化为T[]的方法

解决Prettier将Array格式化为T[]的问题

要让Prettier把TS接口里的Array<T>自动转换成T[],只需调整Prettier的配置即可,具体步骤如下:

  • 修改Prettier配置文件
    找到项目中的Prettier配置文件(常见的有.prettierrc、.prettierrc.json、prettier.config.js等),添加arrayType配置项并设置为'array'。

    示例(JSON格式配置文件):

    {
      "arrayType": "array",
      // 其他已有的Prettier配置...
      "singleQuote": true,
      "semi": false
    }
    

    示例(JS格式配置文件):

    module.exports = {
      arrayType: 'array',
      // 其他已有的Prettier配置...
      singleQuote: true,
      semi: false
    };
    
  • 检查Prettier版本
    arrayType选项是从Prettier 2.6.0版本开始支持的,如果你的项目使用的Prettier版本低于这个版本,需要先升级Prettier:

    npm install prettier@latest --save-dev
    # 或者用yarn
    yarn add prettier@latest --dev
    
  • 处理ESLint冲突(如果有)
    如果你同时使用ESLint和Prettier,要确保ESLint的@typescript-eslint/array-type规则不会和Prettier的配置冲突。可以在ESLint配置文件中关闭该规则,或者将其设置为和Prettier一致的选项:

    {
      "rules": {
        "@typescript-eslint/array-type": ["error", { "default": "array" }]
      }
    }
    
  • 保留特定Array格式(可选)
    如果某些接口字段需要保留Array<T>格式,不想被Prettier转换,可以在对应行上方添加// prettier-ignore注释:

    interface User {
      // prettier-ignore
      roles: Array<string>;
      posts: number[]; // 该字段会保持T[]格式
    }
    

内容的提问来源于stack exchange,提问作者XAronX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 10:04:55