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助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

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

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多