TypeScript 註解的語法文件在哪裡?
TypeScript 的註解語法有記錄在任何地方嗎?
請問現在是否支持 C# /// 系統?
答案#1
目前
TypeScript 團隊以及其他參與 TypeScript 的團隊,創建了一個 TSDoc 規範。https://tsdoc.org/
直接來自文件的範例:
export class Statistics {
/**
* Returns the average of two numbers.
*
* @remarks
* This method is part of the {@link core-library#Statistics | Statistics subsystem}.
*
* @param x - The first input number
* @param y - The second input number
* @returns The arithmetic mean of `x` and `y`
*
* @beta
*/
public static getAverage(x: number, y: number): number {
return (x + y) / 2.0;
}
}
過去
TypeScript 使用 JSDoc。例如。
/** This is a description of the foo function. */
function foo() {
}
要學習 jsdoc :https://jsdoc.app/
但你不需要在 JSDoc 中使用類型註解擴展。
你仍然可以(而且應該)使用其他 jsdoc 區塊標籤,例如 @returns 等。
僅僅是一個例子。專注於類型(不是內容)。
JSDoc 版本(在文件中注意類型):
/**
* Returns the sum of a and b
* @param {number} a
* @param {number} b
* @returns {number}
*/
function sum(a, b) {
return a + b;
}
TypeScript 版本(注意類型的位置變動):
/**
* Takes two numbers and returns their sum
* @param a first input to sum
* @param b second input to sum
* @returns sum of a and b
*/
function sum(a: number, b: number): number {
return a + b;
}
答案#2
2020年11月更新
一個網站現在已經上線,提供所有 TSDoc 語法(這太棒了):https://tsdoc.org/
供參考,舊答案:
正確的語法現在是 TSDoc 使用的語法。它將允許您讓 Visual Studio Code 或其他文件工具理解您的註解。
這裡和尤其是這裡提供了語法的良好概述。精確的規範應該會「很快」被寫出來。
另一個值得查看的文件是這個,你可以在裡面看到有用的標準標籤。
注意:你不應該使用 JSDoc,如 TSDoc 主頁所解釋的那樣:為什麼 JSDoc 不能成為標準?不幸的是,JSDoc 語法並沒有被嚴格規範,而是從特定實現的行為中推斷出來的。大多數標準 JSDoc 標籤專注於為普通 JavaScript 提供類型註解,這對於像 TypeScript 這樣的強型別語言而言是無關的問題。TSDoc 不僅解決了這些限制,還應對了一系列更複雜的目標。
答案#3
您也可以使用以下方式添加有關參數、返回值等的信息:
/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
return bar.toString()
}
這將導致像 VS Code 這樣的編輯器將其顯示如下:
答案#4
你可以像在普通 JavaScript 中一樣使用註解:
1 介紹
[...] TypeScript 語法是 ECMAScript 2015(ES2015)語法的超集。
2 個基本概念
[...] 本文件描述了 TypeScript 新增的語法文法 [...]
來源:TypeScript 語言規範
規範中唯一兩次提到「comments」這個詞的是:
1 介紹
[...] TypeScript 也為 JavaScript 程式設計師提供了一個可選的 類型註解 系統。這些類型註解類似於 Closure 系統中找到的 JSDoc 注解,但在 TypeScript 中它們直接整合到語言語法中。這種整合使程式碼更易讀,並減少將類型註解與其對應變數同步的維護成本。
11.1.1 原始檔案依賴性
[...] 以
/// <reference path="..."/>形式的註解會新增對路徑參數中指定的來源檔案的依賴。該路徑是相對於包含該來源檔案的目錄來解析的。

