利用JSDoc在JS中使用TS功能

740 阅读1分钟

类型标注@type

/** @type { any } */
const anyType = []

// 解构类型
/** @type { [string, number] } */
const [first, second] = anyType

// 对象解构同理
/** @type { { a: string, b: number } } */
const { a, b } = any

泛型@template

/** 
 * @template { Record<keyof any, any> } T 
 * @template { keyof T } K 
 * @param { T } obj 
 * @param { K } key 
 * @returns { T[K] } value 
 */ 
function getVal(obj, key) { 
  return obj[key]
}

或者直接用TypeScript写

/** 
 * @type { <T extends Record<keyof any, any>, K extends keyof T>(obj: T, key: K) => T[K] } 
 */

泛型参数默认值

/**
 * @template { Element } [T = Element]
 * @typedef { T | () => T } Getter
 */
// 相当于
type Getter<T extends Element = Element> = T | () => T

类型断言T as U

使用括号包裹要改变类型的变量,在前面用@type

const a = 12
const b = /**@type {string}*/(/**@type {unknown}*/(a))
const b = a as unknown as string

// as const
const c = /**@type { const }*/([1, 2, 3])
const c = [1, 2, 3] as const

函数重载

使用TypeScript写

/**
 * @type {{
 *   (a: any) => any; 
 *   (a: any, b: any) => any;
 * }}
 */
function someFn() {/***/}

或者手动判断

/** 
 * @template { Record<keyof any, any> } T 
 * @template { keyof T | (keyof T)[] } K 
 * @param { T } obj 
 * @param { K } key 
 * @return { K extends any[] ? T : T[K] } 
 */