TypeScript基礎入門之Javascript檔案型別檢查(四)
繼續上篇文章【ofollow,noindex">TypeScript基礎入門之Javascript檔案型別檢查(三) 】
@param 和 @returns
@param使用與@type相同的型別語法,但添加了引數名稱。 通過用方括號括起名稱,也可以宣告該引數是可選的:
// Parameters may be declared in a variety of syntactic forms /** * @param {string}p1 - A string param. * @param {string=} p2 - An optional param (Closure syntax) * @param {string} [p3] - Another optional param (JSDoc syntax). * @param {string} [p4="test"] - An optional param with a default value * @return {string} This is the result */ function stringsStringStrings(p1, p2, p3, p4){ // TODO }
同樣,對於函式的返回型別:
/** * @return {PromiseLike<string>} */ function ps(){} /** * @returns {{ a: string, b: number }} - May use '@returns' as well as '@return' */ function ab(){}
@typedef, @callback, 和 @param
@typedef可用於定義複雜型別。 類似的語法適用於@param。
/** * @typedef {Object} SpecialType - creates a new type named 'SpecialType' * @property {string} prop1 - a string property of SpecialType * @property {number} prop2 - a number property of SpecialType * @property {number=} prop3 - an optional number property of SpecialType * @prop {number} [prop4] - an optional number property of SpecialType * @prop {number} [prop5=42] - an optional number property of SpecialType with default */ /** @type {SpecialType} */ var specialTypeObject;
您可以在第一行使用物件或物件。
/** * @typedef {object} SpecialType1 - creates a new type named 'SpecialType' * @property {string} prop1 - a string property of SpecialType * @property {number} prop2 - a number property of SpecialType * @property {number=} prop3 - an optional number property of SpecialType */ /** @type {SpecialType1} */ var specialTypeObject1;
@param允許一次性型別規範使用類似的語法。 請注意,巢狀屬性名稱必須以引數名稱為字首:
/** * @param {Object} options - The shape is the same as SpecialType above * @param {string} options.prop1 * @param {number} options.prop2 * @param {number=} options.prop3 * @param {number} [options.prop4] * @param {number} [options.prop5=42] */ function special(options) { return (options.prop4 || 1001) + options.prop5; }
@callback類似於@typedef,但它指定了一個函式型別而不是一個物件型別:
/** * @callback Predicate * @param {string} data * @param {number} [index] * @returns {boolean} */ /** @type {Predicate} */ const ok = s => !(s.length % 2);
當然,任何這些型別都可以在單行@typedef中使用Typescript語法宣告:
/** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */ /** @typedef {(data: string, index?: number) => boolean} Predicate */
@template
您可以使用@template標記宣告泛型型別:
/** * @template T * @param {T} p1 - A generic parameter that flows through to the return type * @return {T} */ function id(x){ return x }
使用逗號或多個標籤宣告多個型別引數:
/** * @template T,U,V * @template W,X */
您還可以在型別引數名稱之前指定型別約束。 只限列表中的第一個型別引數:
/** * @template {string} K - K must be a string or string literal * @template {{ serious(): string }} Seriousalizable - must have a serious method * @param {K} key * @param {Seriousalizable} object */ function seriousalize(key, object) { // ???? }
未完待續...