当使用 TypeScript 检查 JavaScript 代码时,如何转换为与推断不同的类型?Typescript 具有<Type>
和as Type
语法,但这些在 JavaScript 中无效。
/**
* @param {{id: string, value: number}} details - object with required properties
*/
function stringifyObject(details) {
return `${details.id}: ${details.value}`;
}
const testValue = {id: 'no-value'};
stringifyObject(testValue); // want to cast testValue to ignore missing property
stringifyObject(/** @type {any} */ testValue); // this doesn't work
Run Code Online (Sandbox Code Playgroud)
Chi*_*hic 58
评论/** @type */
很接近。根据TypeScript 手册,它只需要在被转换的值周围加上括号。
TypeScript 借用了 Google Closure 的强制转换语法。这允许您通过在任何带括号的表达式之前
@type
添加标记来将类型转换为其他类型。
因此,在最初的示例中,您将编写以下内容:
// Wrap value being cast in parenthesis
stringifyObject(/** @type {any} */ (testValue));
Run Code Online (Sandbox Code Playgroud)
答案已经在另一篇文章中给出了。
但要添加更多用法:
如果您想让类型转换在下面的所有代码行中可用,请使用此
node_curr = /** @type {Element} */ (node_curr); // working for this line & all the lines below
node_curr.outerHTML;
Run Code Online (Sandbox Code Playgroud)
维维
// #>>> an example usage
const elt_main = $('<div></div>')[0];
const treeWalker = document.createTreeWalker(elt_main, NodeFilter.SHOW_ALL);
const arr_html_EltMain = [];
let html_curr;
let node_curr;
while ((node_curr = treeWalker.nextNode())) {
const nt = node_curr.nodeType;
if (nt === Node.TEXT_NODE) {
html_curr = /** @type {Text} */ (node_curr).textContent;
arr_html_EltMain.push(html_curr);
} else if (nt === Node.ELEMENT_NODE) {
html_curr = /** @type {Element} */ (node_curr).outerHTML; // << the Type cast / autocompletion will only apply to this particular line,
// // any reference below this line will fall back to original Type
// // also, if you hover to the variable, it appears to be still the old Type (though autocompletion works)
arr_html_EltMain.push(html_curr);
}
}
// #>>>
// @note: about the paranthesis -- only enclose it for the variable, not need to include the @type
(/** @type {Element} */ (node_curr)).outerHTML; // works, but unnecessary
/** @type {Element} */ (node_curr).outerHTML; // use this
// #>>>
// compare & the correct way to use
/** @type {Element} */ node_curr = node_curr; // not_working
node_curr; // not_working
(/** @type {Element} */ node_curr) = node_curr; // not_working
node_curr; // not_working
/** @type {Element} */ (node_curr) = node_curr; // working only for this line
node_curr; // not_working
node_curr = /** @type {Element} */ node_curr; // not_working
node_curr; // not_working
node_curr = (/** @type {Element} */ node_curr); // not_working
node_curr; // not_working
node_curr = /** @type {Element} */ (node_curr); // working for this line & all the lines below
node_curr; // working
node_curr; // working
node_curr; // working
// #>>>
// @note: if you want to let the type cast be available in all the code lines below, use this
node_curr = /** @type {Element} */ (node_curr); // working for this line & all the lines below
node_curr.outerHTML;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7775 次 |
最近记录: |