Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
¿Cómo especificar el tipo de un generador infinito?

Aquí hay un ejemplo de código 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)

La función gen genera una secuencia infinita de números. Así que no necesito comprobar si está terminado.

¿Es posible eliminar el error de verificación de tipo en el segundo caso? Aquí hay una pregunta similar: Cómo evitar el tipo vacío en los generadores Typescript . Se dieron las siguientes sugerencias:

  1. compruebe primero si lo hecho es cierto y actúe en consecuencia (regreso anticipado, lanzamiento, lo que necesite);
  2. si sabe que el iterador siempre devolverá un valor, puede usar una afirmación no nula.

Pero no quiero marcar done . Y no puedo agregar una afirmación que no sea nula, porque es JavaScript, no TypeScript. ¿Podría sugerir cómo eliminar el error?

Aquí está 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"] }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

TypeScript lo protege de g.return() . No existe una función de generador que nunca se pueda done . El método Generator.prototype.return() puede incluso llamarse implícitamente cuando se usan objetos generadores en bucles 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());

about 4 years ago · Juan Pablo Isaza Report

0

No creo que esto sea un problema con Typescript, ya que se supone que detecta posibles errores de código como este.

Si está absolutamente seguro de que el generador no devolverá un valor nulo, podría escribir explícitamente el tipo así: const y = (g.next().value as number) * 2;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!