简体   繁体   中英

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ A: number; B: number

so I have a function which will take string of upperCase letters and each individual letter has value as stated in alphabet object. Yet I have troubles writing it in typescript. Here is code which is working in javascript:

export const alphabet = {
  A: 1,
  B: 2,
  C: 3,
  D: 4,
  E: 5,
  F: 6,
  G: 7,
  H: 8,
  I: 9,
  J: 10,
  K: 11,
  L: 12,
  M: 13,
  N: 14,
  O: 15,
  P: 16,
  Q: 17,
  R: 18,
  S: 19,
  T: 20,
  U: 21,
  V: 22,
  W: 23,
  X: 24,
  Y: 25,
  Z: 26,
};

const adressDecoder = () => {
  let startColumnString = ["A", "A"]

  let startColumn = startColumnString.reduce((prev, curr) => {
    if (prev === 0) return alphabet[curr];
    return prev * 26 + alphabet[curr];
  }, 0);

  console.log(startColumn);
};

adressDecoder()

and here are errors: 在此处输入图像描述

在此处输入图像描述

So I tried to cast type to alphabet object, but I did it incorrect, and now console.log() returns undefined

interface Alphabet {
  [key: string]: number;
}

export const alphabet: Alphabet = {
  A: 1,
  B: 2,
  C: 3,
  D: 4,
  E: 5,
  F: 6,
  G: 7,
  H: 8,
  I: 9,
  J: 10,
  K: 11,
  L: 12,
  M: 13,
  N: 14,
  O: 15,
  P: 16,
  Q: 17,
  R: 18,
  S: 19,
  T: 20,
  U: 21,
  V: 22,
  W: 23,
  X: 24,
  Y: 25,
  Z: 26,
};

const adressDecoder = () => {
  let startColumnString = ["A", "A"]

  let startColumn = startColumnString.reduce((prev: number, curr: string) => {
    if (prev === 0) {
      let result: number = alphabet[curr];
      return result;
    }
    let result: number = prev * 26 + alphabet[curr];
    return result;
  }, 0);

  console.log(startColumn);// should be 27
};

adressDecoder()

How to properly define interface/type of alpabet object?

It will return undefined because the first reduce iteration, the prev variable will be equal to zero, and with if condition

if (prev === 0) return alphabet[curr];

There is no key in the alphabet object equal to AA

To define properly type of alpabet object use type AlphabetType = keyof typeof alphabet; like so

export const alphabet = {
  A: 1,
  B: 2,
  C: 3,
  D: 4,
  E: 5,
  F: 6,
  G: 7,
  H: 8,
  I: 9,
  J: 10,
  K: 11,
  L: 12,
  M: 13,
  N: 14,
  O: 15,
  P: 16,
  Q: 17,
  R: 18,
  S: 19,
  T: 20,
  U: 21,
  V: 22,
  W: 23,
  X: 24,
  Y: 25,
  Z: 26
} as const;
type AlphabetType = keyof typeof alphabet;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM