我正在寻找一种使用 JSDoc 获取对象属性名称作为类型的方法。
设一个名为
Record
的对象的 typedef
/**
* @typedef {{
date: string,
a1: string,
a2: string,
}} Record
*/
我希望变量
fields
被记录为等于对象的属性 - 这意味着对于这个例子:'date' | 'a1' | 'a2'
/**
* @type {*keyof Record??*} in this case, this will be equal to @type {'date' | 'a1' | 'a2'}
*/
let fields = 'a1';
Typescript 提供了 keyof 关键字,它就是这样做的。不幸的是,我正在使用的系统不支持打字稿:\
/*
* @typedef {{
* date: string,
* a1: string,
* a2: string,
* }} Record
*/
/** @type {Record['date']|Record['a1']|Record['a2']}*/
let fileds = 'a1';
试试这个
-新编辑-
如果您不想列出类型。也许你想尝试这种方式。
/** @typdef {string} RecordProperty */
/*
* @typedef {{
* date: RecordProperty,
* a1: RecordProperty,
* a2: RecordProperty,
* }} Record
*/
/** @type {RecordProprty} */
let fileds = 'a1';
您可以先声明元组(或在另一个
@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,
};