0

I get a compilation error:

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ G: string; C: string; T: string; A: string; }'.
  No index signature with a parameter of type 'number' was found on type '{ G: string; C: string; T: string; A: string; }'.(7053)

on Transcriptor.DNA_TO_RNA_NUCLEOTIDES[dnsNucleotide] in the following code:

class Transcriptor {

    static readonly DNA_TO_RNA_NUCLEOTIDES = { 'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U' }

    toRna(dnaStrand: string) {
        let rnaStrand: string = ""
        const dnaAsArray: string[] = Array.from(dnaStrand)
        for (const dnsNucleotide in dnaAsArray) {
            const rnaNucleotide: string = Transcriptor.DNA_TO_RNA_NUCLEOTIDES[dnsNucleotide]
            rnaStrand += rnaNucleotide
        }
        return rnaStrand
    }
}

export default Transcriptor

I would understand that this happened if dnsNucleotide could be any, but in this case it's a string, so where is number being inferred from?

I know I can fix it with static readonly DNA_TO_RNA_NUCLEOTIDES: { [key: string]: string} = {...}

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
antonro
  • 449
  • 2
  • 4
  • 10
  • 1
    `for (const var in arr) {` iterates over the *indices* of an array. – jonrsharpe Dec 08 '20 at 10:41
  • Does this answer your question? [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – Liam Dec 08 '20 at 10:41
  • [...`for...in` statement, but for iterating arrays for-in should be avoided, that statement is meant to enumerate object properties.](https://stackoverflow.com/a/3010848/542251) – Liam Dec 08 '20 at 10:42
  • @jonrsharpe but if I hover with the mouse over `const dnsNucleotide`, the IDE (VS Code) tells me that it's of type `string` – antonro Dec 08 '20 at 10:46
  • I'm not sure why, you can see with e.g. `for (const val in ["foo", "bar", "baz"]) { console.log(val) }` that you get `0`, `1`, `2`. – jonrsharpe Dec 08 '20 at 10:49
  • @jonrsharpe I also don't understand how, if the problem is how I iterate the array, `static readonly DNA_TO_RNA_NUCLEOTIDES: { [key: string]: string}` solves the problem. – antonro Dec 08 '20 at 10:50

0 Answers0