我对此束手无策。似乎它应该可以工作,我已经为此苦苦挣扎了几个小时,但我不确定出了什么问题。这是我能想到的最小的例子。我什至有一个类型后卫。
/** @typedef {{ a: string }} TypeA*/
/** @typedef {{ b: string }} TypeB*/
/** @typedef {(TypeA | TypeB) } TypeC */
/** @type {TypeC} */
let typeC;
console.log(typeC.b) // autocompletion for property b doesn't work
我得到错误:Property 'b' does not exist on type '{ a: string; } | { b: string; }'.
Property 'b' does not exist on type '{ a: string; }'.ts(2339)
最佳答案
我发现一个 jsdoc 风格的类型保护可以让我访问 TypeC 的属性,如果我能够将其键入为 TypeB。
/** @typedef {{ a: string }} TypeA*/
/** @typedef {{ b: string }} TypeB*/
/** @typedef {(TypeA | TypeB) } TypeC */
/**
* @param {*} value
* @returns {value is TypeB}
*/
function typeIsB(value) {
return true;
}
/** @type {TypeC} */
let typeC;
if (typeIsB(typeC)) {
console.log(typeC.b) // no error, autocomplete works when typing typeC.b
}
自动完成工作的屏幕截图:关于javascript - 对象不工作的 JsDoc 联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65294867/