TypeScript Tutorial
TypeScript Comments
Comments are for people. The compiler skips // lines and /* blocks */.
The compiler ignores comments
A comment is text you leave in the source so a human can follow the program. tsc does not compile it. It does not change output. Use comments to record why a line exists, not to repeat what the code already shows.
Example
// This program greets the user once.
console.log("Hello");Run this in /typescript/try with Try it in TypeScript. The TypeScript editor compiles with tsc. Comments never appear in the output pane.
Line comments with //
Two slashes start a comment that runs to the end of that line. You can put // on its own line or after a statement. Everything after // on that line is skipped.
Example
const n: number = 10; // starting inventory
console.log(n);
// console.log("skip this line while testing");
console.log("still running");Commenting out a statement is a common way to disable it while you test. Uncomment it by deleting the// when you want that line back.
Block comments with /* */
/* starts a comment that can span several lines. */ ends it. Everything between those markers is skipped, including what would otherwise be code.
Example
/*
Print a short header, then a number.
Block comments can cover more than one line.
*/
console.log("total");
console.log(42);Blocks do not nest
You cannot put one /* ... */ inside another. The first */ ends the comment. The rest of the inner comment becomes ordinary code, and tsc reports a mess of errors.
If you wrap a region in /* */ and that region already contains */, the comment stops too early. Prefer // on each line when you disable a chunk of code.
What to write
Name the intent, the unit, or the rule a reader would miss. Do not narrate n = n + 1 as “add one.” Stale comments are worse than none: when you change the code, change the comment in the same edit.
| Weak | Useful |
|---|---|
count = count + 1; // increment count | count = count + 1; // skip the header row |
price = price * 0.9; // multiply | price = price * 0.9; // 10 percent loyalty discount |
Comments are not strings
Text in quotes is data. The program can print it. Text after // is not data. If you need the user to see a message, put it in console.log, not in a comment.
Example
const label: string = "visible to the user";
// This line is only for the person reading the source.
console.log(label);Next: variables, so those printed numbers have names.