如何设置字符串的智能感知以避免在 JavaScript 中使用 VS 代码输入无效值

How to set an intelliSense of strings to avoid typing invalid values in JavaScript with VS Code

当我在 VS Code 中编写内置关键字 typeof 时,我发现了一个很酷的智能感知功能, 它显示了一个特定的选项列表,其中包含 typeof returns 的所有有效值,如下图所示。

此功能使我们在使用该函数时避免键入无效结果。

所以我想知道我们可以使用 jsdoc 或 eslint 为自定义函数或数组创建智能感知吗?如果没有,是否有其他工具可以实现?

var dayOptions = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday'
]

function checkDay(option){ // I don't want to let user input values outside the array above
  // code
}

checkDay('Friday') // I want to make an intelliSense list here
checkDay('other') // I want VS Code show me something wrong here

您可以使用 JSDoc 语法:

@param {'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday'} option

Argument of type '"other"' is not assignable to parameter of type '"Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday"'.