Home > Blockchain >  How To Assign a Type to an Empty Object in Typescript?
How To Assign a Type to an Empty Object in Typescript?

Time:10-25

I'm trying to create a counter that says which character appears the most in a string.

function maxChar(str: string) {
  const strObj = {}
  let maxCount = 0
  let maxChar = ""

  for (let char of str) {
    strObj[char] = strObj[char]   1 || 1 
  }
  for (let key in strObj) {
    if (strObj[key] > maxCount) {
      maxCount = strObj[key]
      maxChar = key
    }
  }
  return maxChar 
}

However, Typescript underscores strObj[char] and strObj[key], giving error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

Apparently strObj = {} needs a type assigned, but I have no idea how to assign a type to an empty object.

CodePudding user response:

You are using strObj like a dictionary whose keys are any character and whose values are number (or undefined). The closest thing built into TypeScript is a type with a string index signature:

const strObj: { [k: string]: number } = {} 

Now the compiler will let you index into strObj with any string-valued key (including all the single-character-long strings), and it will allow you to read/write a number value from it. (Technically maybe it should be more careful with undefined, but most people do the right thing with undefined and index signatures, so the compiler ignores it. If you really care you can write number | undefined or enable the --noUncheckedIndexedAccess compiler option, but all that will do is make it more annoying to write your code.)

Anyway, now the rest of your code example will compile with no error.

Note that the type {[k: string]: number} can also be written as Record<string, number> using the Record<K, V> utility type. Either way corresponds to an object type which allows any string as a key and whose value, if present, will be of type number.

Playground link to code

  • Related