最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JSDoc: how to define a type that's equal to object's property names- like Typescript's keyo

programmeradmin1浏览0评论

I'm looking for a way to get an object's property names as a type using JSDoc.

Let there be a typedef of an object named Record

/**
 * @typedef {{
      date: string,
      a1: string,
      a2: string,
   }} Record
 */

I want the variable fields to be documented as equal to the object's properties- which means for this example: 'date' | 'a1' | 'a2'

/**
 * @type {*keyof Record??*} in this case, this will be equal to @type {'date' | 'a1' | 'a2'}
 */
let fields = 'a1';

Typescript provides the keyof keyword, which does just that. unfortunately, the system I'm working on does not support typescript :\

I'm looking for a way to get an object's property names as a type using JSDoc.

Let there be a typedef of an object named Record

/**
 * @typedef {{
      date: string,
      a1: string,
      a2: string,
   }} Record
 */

I want the variable fields to be documented as equal to the object's properties- which means for this example: 'date' | 'a1' | 'a2'

/**
 * @type {*keyof Record??*} in this case, this will be equal to @type {'date' | 'a1' | 'a2'}
 */
let fields = 'a1';

Typescript provides the keyof keyword, which does just that. unfortunately, the system I'm working on does not support typescript :\

Share Improve this question asked Jun 1, 2022 at 9:24 ar36elar36el 1,0861 gold badge11 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2
/*
* @typedef {{
* date: string,
* a1: string,
* a2: string,
* }} Record
*/

/** @type {Record['date']|Record['a1']|Record['a2']}*/
let fileds = 'a1';

Try this

-New Edit-

If you don't want to list up the types. Maybe you want to try this way.

/** @typdef {string} RecordProperty */

/*
* @typedef {{
* date: RecordProperty,
* a1: RecordProperty,
* a2: RecordProperty,
* }} Record
*/

/** @type {RecordProprty} */
let fileds = 'a1';

Instead of declaring a enum-like object, you can just declare the tuple first(or in another @typedef):

const OPTIONS = /** @type {const} */ (['one', 'two']);
/**
 * @type {typeof OPTIONS[number]}
 * @see OPTIONS
 */
const option = 'two';
// error TS2322: Type '"four"' is not assignable to type '"one" | "two"'.
// /** @type {typeof OPTIONS[number]} */ const invalidOption = 'four';

/**
 * @type {{[Key in OPTIONS[number]]: any}}
 */
const optionObj = {
  one: 1,
  two: 2,
  // error TS2322: Type '{ one: number; two: number; four: number; }' is not assignable to type '{ one: any; two: any; }'.
  // four: 4,
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论