Ccmmutty logo
Commutty IT
3 min read

Javascript My Cheatsheat

https://cdn.magicode.io/media/notebox/70855401-8930-45da-86d8-139745a6cc69.jpeg

JSDoc と型チェック

vscode
//@ts-check
///<reference path="./module.js"/>
/** https://ics.media/entry/6789/ より **/
//@ts-check
class CountManager {
  constructor() {
    /**
     * カウントの数値
     * @type {number}
     */
    this._count = 0;
  }

  /** カウントの数値をインクリメント */
  addCount() {
    this._count++;
  }

  /**
   * カウントの数値を取得
   * @return {number} カウントの数値
   */
  getCount() {
    return this._count;
  }
}

/** @type {CountManager} クラスを格納  */ 
const cm = new CountManager();
/** @type {number} 例  */ 
const item = cm.getCount();

/**
 * メッセージです。
 * @type {string}
 */
 const messsage = "こんにちは";

 /**
  * 数値の型の例です。
  * @type {number}
  */
 let count = 0;
 
 /**
  * 配列の型の例です。
  * @type {number[]}
  */
 const list = [];
 
 /**
  * オブジェクトの型の例です。
  * @type {{name: string, age: number}}
  */
 const obj = { name: "鈴木", age: 42 };
/** @type {(num1: number, num2: number) => number)} */
const fn = (num1, num2) => {
  return num1 + num2
}
/** @type {'red'|'green'} */
let color
/** @enum {number} */
const color = {
  red: 0,
  green: 1,
  blue: 2
}
/** @type {Array<string|number>} */
let a = ["2", 1]
/**
 * @callback Calc
 * @param {number} num1
 * @param {number} num2
 * @returns {number}
 */

/** @type {Calc} */
const add = (num1, num2) => {
  return num1 + num2
}

/** @type {Calc} */
const sub = (num1, num2) => {
  return num1 - num2
} 
// @ts-check
class User {
  /**
   * 
   * @param {string} name 
   * @param {number} age 
   */
  constructor(name, age) {
    /** @readonly */
    this.id = 1
  
    /** @public */
    this.name = name
  
    /** @private */
    this.age = age
  }
}

const user = new User('user1', 24)

user.name // ok
user.age // Property 'age' is private and only accessible within class 'User'.
user.id = 2 // Cannot assign to 'id' because it is a read-only property.
/**
 * @typedef User
 * @property {string} name ユーザー名
 * @property {number} age ユーザーの年齢
 * 
 */
{{a: number, b: string, c}} myObj も
/**
 * @type {String}
 * @type {Number}
 * @type {BigInt}
 * @type {Boolean}
 * @type {Symbol}
 */
nullableなら?型, non nullableなら!型と書きます。
条件 (三項) 演算子
const type = (condition ? "true" : "false)"

Discussion

コメントにはログインが必要です。