The Typescript `type "String" cannot be used as an index type. `

clipboard.png

  • this.localize is an object
  • method getLocalize returns the value
  • in this.localize through the parameter key passed in.

how to solve the error of asking for help?

the complete code is as follows:

import * as path from "path"
import * as fs from "fs"

class Localize {
  locale: String
  localize: Object

  constructor() {
    this.init(JSON.parse(process.env.VSCODE_NLS_CONFIG || ""))
    this.locale = ""
    this.localize = {}
  }

  init({ locale }: { locale: String }) {
    this.locale = locale
    const localName = (!locale || locale === "en") ? "" : "." + locale
    const localePackagePath = path.resolve(__dirname, `../../package.nls${localName}.json`)
    if (fs.existsSync(localePackagePath)) {
      this.localize = require(localePackagePath)
    } else {
      this.localize = require(path.resolve(__dirname, "../../package.nls.json"))
    }
  }

  getLocalize(key: String) {
    let res = this.localize[key] || key
    if (arguments.length > 1) {
      const params = Object.assign([], arguments)
      params.forEach((val, i) => {
        if (i > 0) res = res.replace(`{${i}}`, val)
      })
    }
    return res
  }
}

const localize = new Localize()

export default localize
Jun.25,2022

Don't use the String object, use the string type, and define your localise:

import * as path from 'path'
import * as fs from 'fs'

class Localize {
  locale: String
    localize: {
        [k: string]: any
    }

  constructor() {
    this.init(JSON.parse(process.env.VSCODE_NLS_CONFIG || ''))
    this.locale = ''
    this.localize = {}
  }

  init({ locale }: { locale: string }) {
    this.locale = locale
    const localName = (!locale || locale === 'en') ? '' : '.' + locale
    const localePackagePath = path.resolve(__dirname, `../../package.nls${localName}.json`)
    if (fs.existsSync(localePackagePath)) {
      this.localize = require(localePackagePath)
    } else {
      this.localize = require(path.resolve(__dirname, '../../package.nls.json'))
    }
  }

  getLocalize(key: string) {
    let res = this.localize[key] || key
    if (arguments.length > 1) {
      const params = Object.assign([], arguments)
      params.forEach((val, i) => {
        if (i > 0) res = res.replace(`{${i}}`, val)
      })
    }
    return res
  }

say a few more sentences, the code is a little rough, require seems unnecessary

Menu