clean-code-typescript

clean-code-typescript

TypeScript 代码整洁之道实践指南

clean-code-typescript 项目将 Clean Code 原则应用于 TypeScript,为开发者提供编写高质量代码的指导。该项目涵盖变量命名、函数设计和对象结构等多个方面,通过对比优劣代码示例,深入解析编码原则。这一资源旨在帮助 TypeScript 开发者提升代码可读性、可重用性和可维护性,是改善编程实践的有力工具。

TypeScript代码规范函数设计变量命名Clean CodeGithub开源项目

clean-code-typescript Tweet

Clean Code concepts adapted for TypeScript.
Inspired from clean-code-javascript.

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
  6. SOLID
  7. Testing
  8. Concurrency
  9. Error Handling
  10. Formatting
  11. Comments
  12. Translations

Introduction

Humorous image of software quality estimation as a count of how many expletives
you shout when reading code

Software engineering principles, from Robert C. Martin's book Clean Code, adapted for TypeScript. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in TypeScript.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Our craft of software engineering is just a bit over 50 years old, and we are still learning a lot. When software architecture is as old as architecture itself, maybe then we will have harder rules to follow. For now, let these guidelines serve as a touchstone by which to assess the quality of the TypeScript code that you and your team produce.

One more thing: knowing these won't immediately make you a better software developer, and working with them for many years doesn't mean you won't make mistakes. Every piece of code starts as a first draft, like wet clay getting shaped into its final form. Finally, we chisel away the imperfections when we review it with our peers. Don't beat yourself up for first drafts that need improvement. Beat up the code instead!

⬆ back to top

Variables

Use meaningful variable names

Distinguish names in such a way that the reader knows what the differences offer.

Bad:

function between<T>(a1: T, a2: T, a3: T): boolean { return a2 <= a1 && a1 <= a3; }

Good:

function between<T>(value: T, left: T, right: T): boolean { return left <= value && value <= right; }

⬆ back to top

Use pronounceable variable names

If you can’t pronounce it, you can’t discuss it without sounding like an idiot.

Bad:

type DtaRcrd102 = { genymdhms: Date; modymdhms: Date; pszqint: number; }

Good:

type Customer = { generationTimestamp: Date; modificationTimestamp: Date; recordId: number; }

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

function getUserInfo(): User; function getUserDetails(): User; function getUserData(): User;

Good:

function getUser(): User;

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code we do write must be readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools like ESLint can help identify unnamed constants (also known as magic strings and magic numbers).

Bad:

// What the heck is 86400000 for? setTimeout(restart, 86400000);

Good:

// Declare them as capitalized named constants. const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; // 86400000 setTimeout(restart, MILLISECONDS_PER_DAY);

⬆ back to top

Use explanatory variables

Bad:

declare const users: Map<string, User>; for (const keyValue of users) { // iterate through users map }

Good:

declare const users: Map<string, User>; for (const [id, user] of users) { // iterate through users map }

⬆ back to top

Avoid Mental Mapping

Explicit is better than implicit.
Clarity is king.

Bad:

const u = getUser(); const s = getSubscription(); const t = charge(u, s);

Good:

const user = getUser(); const subscription = getSubscription(); const transaction = charge(user, subscription);

⬆ back to top

Don't add unneeded context

If your class/type/object name tells you something, don't repeat that in your variable name.

Bad:

type Car = { carMake: string; carModel: string; carColor: string; } function print(car: Car): void { console.log(`${car.carMake} ${car.carModel} (${car.carColor})`); }

Good:

type Car = { make: string; model: string; color: string; } function print(car: Car): void { console.log(`${car.make} ${car.model} (${car.color})`); }

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Default arguments are often cleaner than short circuiting.

Bad:

function loadPages(count?: number) { const loadCount = count !== undefined ? count : 10; // ... }

Good:

function loadPages(count: number = 10) { // ... }

⬆ back to top

Use enum to document the intent

Enums can help you document the intent of the code. For example when we are concerned about values being different rather than the exact value of those.

Bad:

const GENRE = { ROMANTIC: 'romantic', DRAMA: 'drama', COMEDY: 'comedy', DOCUMENTARY: 'documentary', } projector.configureFilm(GENRE.COMEDY); class Projector { // declaration of Projector configureFilm(genre) { switch (genre) { case GENRE.ROMANTIC: // some logic to be executed } } }

Good:

enum GENRE { ROMANTIC, DRAMA, COMEDY, DOCUMENTARY, } projector.configureFilm(GENRE.COMEDY); class Projector { // declaration of Projector configureFilm(genre) { switch (genre) { case GENRE.ROMANTIC: // some logic to be executed } } }

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the number of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.

Consider using object literals if you are finding yourself needing a lot of arguments.

To make it obvious what properties the function expects, you can use the destructuring syntax. This has a few advantages:

  1. When someone looks at the function signature, it's immediately clear what properties are being used.

  2. It can be used to simulate named parameters.

  3. Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.

  4. TypeScript warns you about unused properties, which would be impossible without destructuring.

Bad:

function createMenu(title: string, body: string, buttonText: string, cancellable: boolean) { // ... } createMenu('Foo', 'Bar', 'Baz', true);

Good:

function createMenu(options: { title: string, body: string, buttonText: string, cancellable: boolean }) { // ... } createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true });

You can further improve readability by using type aliases:

type MenuOptions = { title: string, body: string, buttonText: string, cancellable: boolean }; function createMenu(options: MenuOptions) { // ... } createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true });

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.

Bad:

function emailActiveClients(clients: Client[]) { clients.forEach((client) => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } }); }

Good:

function emailActiveClients(clients: Client[]) { clients.filter(isActiveClient).forEach(email); } function isActiveClient(client: Client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); }

⬆ back to top

Function names should say what they do

Bad:

function addToDate(date: Date, month: number): Date { // ... } const date = new Date(); // It's hard to tell from the function name what is added addToDate(date, 1);

Good:

function addMonthToDate(date: Date, month: number): Date { // ... } const date = new Date(); addMonthToDate(date, 1);

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.

Bad:

function parseCode(code: string) { const REGEXES = [ /* ... */ ]; const statements = code.split(' '); const tokens = []; REGEXES.forEach((regex) => { statements.forEach((statement) => { // ... }); }); const ast = []; tokens.forEach((token) => { // lex... }); ast.forEach((node) => { // parse... }); }

Good:

const REGEXES = [ /* ... */ ]; function parseCode(code: string) { const tokens = tokenize(code); const syntaxTree = parse(tokens); syntaxTree.forEach((node) => { // parse... }); } function tokenize(code: string): Token[] { const statements = code.split(' '); const tokens: Token[] = []; REGEXES.forEach((regex) => { statements.forEach((statement) => { tokens.push( /* ... */ ); }); }); return tokens; } function parse(tokens: Token[]): SyntaxTree { const syntaxTree: SyntaxTree[] = []; tokens.forEach((token) => { syntaxTree.push( /* ... */ ); }); return syntaxTree; }

⬆ back to top

Remove duplicate code

Do your absolute best to avoid duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.

Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. If you only have one list, there's only one place to update!

Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow the SOLID principles. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise, you'll find yourself updating multiple places anytime you want to change one thing.

Bad:

function showDeveloperList(developers: Developer[]) { developers.forEach((developer) => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); const data = { expectedSalary, experience, githubLink }; render(data); }); } function showManagerList(managers: Manager[]) { managers.forEach((manager) => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); const data = { expectedSalary, experience, portfolio }; render(data); }); }

Good:

class Developer { // ... getExtraDetails() { return { githubLink: this.githubLink, } } } class Manager { // ... getExtraDetails() { return { portfolio: this.portfolio, } } } function showEmployeeList(employee: (Developer | Manager)[]) { employee.forEach((employee) => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); const extra = employee.getExtraDetails(); const data = { expectedSalary, experience, extra, }; render(data); }); }

You may also consider adding a union type, or common parent class if it suits your abstraction.

class Developer { // ... } class Manager { // ... } type Employee = Developer | Manager function showEmployeeList(employee: Employee[]) { // ... }); }

You should be critical about code duplication. Sometimes there is a tradeoff between duplicated code and increased complexity by introducing unnecessary abstraction. When two implementations from two different modules look similar but live in different domains, duplication might be acceptable and preferred over extracting the common code. The extracted common code, in this case, introduces an indirect dependency between the two modules.

⬆ back to top

Set default objects with Object.assign or destructuring

Bad:

type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; function createMenu(config: MenuConfig) { config.title = config.title || 'Foo'; config.body = config.body || 'Bar'; config.buttonText = config.buttonText || 'Baz'; config.cancellable = config.cancellable !== undefined ? config.cancellable : true; // ... } createMenu({ body: 'Bar' });

Good:

type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; function createMenu(config: MenuConfig) { const menuConfig = Object.assign({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true }, config); // ... } createMenu({ body: 'Bar' });

Or, you could use the spread operator:

function createMenu(config: MenuConfig) { const menuConfig = { title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true, ...config, }; // ... }

The spread operator and Object.assign() are very similar. The main difference is that spreading defines new properties, while Object.assign() sets them. More detailed, the difference is explained in this thread.

Alternatively, you can use destructuring with default values:

type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean }; function createMenu({ title = 'Foo', body = 'Bar', buttonText =

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多