Item 31: Don’t Repeat Type Information in Documentation
May 10, 2024 · View on GitHub
Things to Remember
- Avoid repeating type information in comments and variable names. In the best case it is duplicative of type declarations, and in the worst case it will lead to conflicting information.
- Declare parameters
readonlyrather than saying that you don't mutate them. - Consider including units in variable names if they aren't clear from the type (e.g.,
timeMsortemperatureC).
Code Samples
/**
* Returns a string with the foreground color.
* Takes zero or one arguments. With no arguments, returns the
* standard foreground color. With one argument, returns the foreground color
* for a particular page.
*/
function getForegroundColor(page?: string) {
return page === 'login' ? {r: 127, g: 127, b: 127} : {r: 0, g: 0, b: 0};
}
/** Get the foreground color for the application or a specific page. */
function getForegroundColor(page?: string): Color {
// ...
}
/** Sort the strings by numeric value (i.e. "2" < "10"). Does not modify nums. */
function sortNumerically(nums: string[]): string[] {
return nums.sort((a, b) => Number(a) - Number(b));
}
/** Sort the strings by numeric value (i.e. "2" < "10"). */
function sortNumerically(nums: readonly string[]): string[] {
return nums.sort((a, b) => Number(a) - Number(b));
// ~~~~ ~ ~ Property 'sort' does not exist on 'readonly string[]'.
}
/** Sort the strings by numeric value (i.e. "2" < "10"). */
function sortNumerically(nums: readonly string[]): string[] {
return nums.toSorted((a, b) => Number(a) - Number(b)); // ok
}