Search code examples
javascriptangulartypescriptindex-signature

Typescript: How to remove key from index signature?


In my Angular based web application, we at some point needed a type to hold translations of various strings in different languages. A colleague then implemented this type for that purpose:

export class TranslatedString {
  [language: string]: string;
}

Apparently, this is called an Index Signature, but I never really used it myself so I don't exactly understand how it works. When I inspect an instance of this at runtime, it looks like this:

{de: "TestDE", en: "TestEN", fr: "TestFR"}
de:"TestDE"
en:"TestEN"
fr:"TestFR"
__proto__:{}

I am now in a situation where I need to delete a translation from this type, but I cannot figure out a way to do it. There does not seem to be a remove or delete function which I can call to remove an element via its key. Is there really no way to do this, or how can I remove a translation from an instance of TranslatedString?


Solution

  • At runtime the object you are getting is a normal JavaScript object

    translations = {de: "TestDE", en: "TestEN", fr: "TestFR"}
    

    so a delete should do it:

    delete translations['de']
    
     // or 
    
    delete translations.de