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

104
Views
Texto mecanografiado: genera tipos a partir de un objeto con la interfaz

Es la segunda parte de mi pregunta que se hizo aquí . Me ayudaron con la solución de mi problema anterior, pero una vez que agregué la interfaz para el objeto del alphabet , Typescript dejó de detectar que proporcioné el valor incorrecto.

 interface ICharMap { lower: number upper: number } const alphabet: {[key: string]: ICharMap} = { 'a': {lower: 97, upper: 65}, 'b': {lower: 98, upper: 66} } type Char = keyof typeof alphabet; function printSome(char: Char){ console.log(char) } printSome('c') \\ Typescript does not detect that the incorrect value is passed.
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Podrías hacer algo como esto:

 interface ICharMap { lower: number upper: number } type Letter = 'a' | 'b' const alphabet: Record<Letter, ICharMap> = { 'a': {lower: 97, upper: 65}, 'b': {lower: 98, upper: 66} } function printSome(char: Letter){ console.log(char); console.log(alphabet[char]); // no error; TS knows that char is in alphabet } printSome('c') // error
about 4 years ago · Juan Pablo Isaza Report

0

Es porque su alfabeto tiene {[key: string]} por lo que cuando hace keyof typeof alphabet , devuelve una cadena, con eso puede pasar cualquier cadena.

Si modifica su secuencia de comandos de esta manera, le dirá a TypeScript que debe pasar solo 'a' y 'b'

 interface ICharMap { lower: number upper: number } type keys = 'a' | 'b'; const alphabet: {[key in keys]: ICharMap} = { 'a': {lower: 97, upper: 65}, 'b': {lower: 98, upper: 66} } type Char = keyof typeof alphabet; function printSome(char: Char){ console.log(char) } printSome('c')
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!