Code Formatting
Indentation with Spaces
- Level: Recommendation
Description: Use spaces for indentation. It is recommended to use two spaces in most cases and four spaces for indentation caused by line breaks. Do not use the Tab character. Almost all IDEs and code editors support configuring the Tab key to automatically expand to two spaces. Configure your code editor to use spaces for indentation.
Positive Example:
class DataSource {
id: number = 0
title: string = ''
content: string = ''
}
const dataSource: DataSource[] = [
{
id: 1,
title: 'Title 1',
content: 'Content 1'
},
{
id: 2,
title: 'Title 2',
content: 'Content 2'
}
];
function test(dataSource: DataSource[]) {
if (!dataSource.length) {
return;
}
for (let data of dataSource) {
if (!data || !data.id || !data.title || !data.content) {
continue;
}
// some code
}
// some code
}
Line Length
- Level: Recommendation
- Description: Lines of code should not be too long. Limiting line length can indirectly encourage shorter function and variable names, reduce nesting levels, and improve code readability.
Recommendation: Keep lines within 120 characters. Exceptions are allowed if exceeding 120 characters significantly improves readability and does not hide information.
Exceptions: Lines with commands or URLs over 120 characters can stay as one line for easy copying and pasting. Preprocessed error messages can also remain as one line even if they exceed 120 characters.
Braces in Control Structures
- Level: Recommendation
Description: Always use braces {} for the bodies of if, for, do, while statements. Omitting braces can lead to errors and reduce code clarity.
Negative Example:
if (condition)
console.log('success');
for (let idx = 0; idx < 5; ++idx)
console.log(idx);
- Positive Example:
if (condition) {
console.log('success');
}
for (let idx = 0; idx < 5; ++idx) {
console.log(idx);
}
Indentation in switch Statements
- Level: Recommendation
Description: In switch statements, case and default should be indented by one level (two spaces). Statements after a switch label should be indented by an additional level (two spaces).
Positive Example:
switch (condition) {
case 0: {
doSomething();
break;
}
case 1: {
doOtherthing();
break;
}
default:
break;
}
Top comments (0)