MST

星途 面试题库

面试题:TypeScript代码格式化时遇到复杂类型嵌套的处理方案

假设你有一段TypeScript代码,包含多层嵌套的类型,如嵌套的接口、泛型类型等。在使用Prettier等格式化工具进行格式化时,可能会出现类型结构显示混乱或不符合预期的情况。请阐述你会如何优化格式化配置或者编写自定义的格式化逻辑,以确保复杂类型嵌套的代码在格式化后依然保持清晰易读,并且类型语法完全正确。
29.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 优化Prettier配置
    • 使用.prettierrc文件
      • 在项目根目录创建.prettierrc文件(可以是JSON、YAML或JavaScript格式)。
      • 配置printWidth选项,根据项目风格和屏幕宽度合理设置,例如120,这样较长的类型定义不会被过度换行导致混乱。例如:
{
    "printWidth": 120
}
  • 调整tabWidthuseTabs
    • 如果使用空格缩进,tabWidth设为合适的空格数,如4;如果使用制表符,设置useTabstrue
{
    "tabWidth": 4,
    "useTabs": false
}
  • singleQuotetrailingComma
    • 统一使用单引号singleQuote: true,并且合理设置trailingCommaes5all,这样在多行类型定义中,逗号的位置更一致,易于阅读。
{
    "singleQuote": true,
    "trailingComma": "es5"
}
  1. 编写自定义格式化逻辑(以ESLint插件为例)
    • 创建ESLint插件
      • 初始化一个npm项目npm init -y
      • 安装必要依赖npm install eslint - - save - dev
      • 创建插件文件,例如eslint - plugin - custom - types.js
    • 编写规则
      • 在插件文件中定义规则,例如检查嵌套接口的缩进是否正确。
module.exports = {
    rules: {
        'nested - interface - indent': function (context) {
            return {
                InterfaceDeclaration(node) {
                    if (node.body && node.body.body) {
                        const firstChild = node.body.body[0];
                        if (firstChild) {
                            const indent = firstChild.range[0] - node.range[0];
                            for (const child of node.body.body) {
                                const childIndent = child.range[0] - node.range[0];
                                if (childIndent!== indent) {
                                    context.report({
                                        node: child,
                                        message: 'Nested interface members should have consistent indent'
                                    });
                                }
                            }
                        }
                    }
                }
            };
        }
    },
    configs: {
        recommended: {
            rules: {
                'custom - types/nested - interface - indent': 'error'
            }
        }
    }
};
  • 在项目中使用
    • .eslintrc文件中配置使用该插件。
{
    "plugins": ["custom - types"],
    "extends": ["plugin:custom - types/recommended"]
}
  1. 结合IDE设置
    • 在VS Code中,确保Prettier插件和ESLint插件都正确安装和配置。
    • 在VS Code的settings.json中,可以进一步微调格式化选项,例如设置editor.formatOnSavetrue,确保保存文件时自动格式化。
{
    "editor.formatOnSave": true
}
  • 对于复杂类型嵌套的代码块,可以使用VS Code的代码折叠功能,将不相关的部分折叠起来,专注于当前查看的类型结构。