這是一個示例 JavaScript 代碼:
/**
* Generates the sequence of numbers.
*
* @param {number} i - The first number.
* @yields {number} The next number.
*/
function* gen(i) {
while (true) {
yield i ;
}
}
const g = gen(1);
// 1st case
// No error here
const n = g.next();
if (!n.done) {
const x = n.value * 2;
console.log(x);
}
// 2nd case
// Error:
// The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
// Other variants of the error for other expressions:
// Type 'number | void' is not assignable to type 'number'.
// Type 'void' is not assignable to type 'number'
const y = g.next().value * 2;
console.log(y)
gen函式生成一個無限的數字序列。所以我不需要檢查它是否完成。
是否可以在第二種情況下消除型別檢查錯誤?這是一個類似的問題:How to Avoid void type in generators Typescript。提出了以下建議:
- 首先檢查 done 是否為真并采取相應措施(提前回傳、拋出,無論您需要什么);
- 如果您知道迭代器將始終回傳一個值,則可以使用非空斷言。
但我不想檢查done。而且我不能添加非空斷言,因為它是 JavaScript,而不是 TypeScript。你能建議如何消除錯誤嗎?
這里是jsconfig.json:
{
"compilerOptions": {
"lib": ["es2021"],
"allowJs": true,
"checkJs": true,
"noEmit": true,
"module": "es2022",
"target": "es2021",
"strict": true,
"strictPropertyInitialization": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowUnusedLabels": false,
"allowUnreachableCode": false,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"importsNotUsedAsValues": "error"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
uj5u.com熱心網友回復:
TypeScript 正在保護您免受g.return(). 不存在永遠不可能存在的生成器函式done。在回圈Generator.prototype.return()中使用生成器物件時,甚至可以隱式呼叫該方法:for...of
function* gen(i) {
while (true) {
yield i ;
}
}
const g = gen(1);
for (const n of g) {
if (n > 5) break;
console.log(n);
}
console.log(g.next());
uj5u.com熱心網友回復:
我認為這不是 Typescript 的問題,因為它應該能夠捕獲像這樣的潛在代碼錯誤。
如果您絕對確定生成器不會回傳空值,則可以像這樣顯式寫出型別:
const y = (g.next().value as number) * 2;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471279.html
標籤:javascript 打字稿
