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 badges2 Answers
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,
};