Enforcing the type of the indexed members of a Typescript object?

后端 未结 8 1670
旧时难觅i
旧时难觅i 2020-11-29 15:15

I would like to store a mapping of string -> string in a Typescript object, and enforce that all of the keys map to strings. For example:

var stuff = {};
st         


        
相关标签:
8条回答
  • 2020-11-29 15:59

    Define interface

    interface Settings {
      lang: 'en' | 'da';
      welcome: boolean;
    }
    

    Enforce key to be a specific key of Settings interface

    private setSettings(key: keyof Settings, value: any) {
       // Update settings key
    }
    
    0 讨论(0)
  • 2020-11-29 16:03
    var stuff: { [key: string]: string; } = {};
    stuff['a'] = ''; // ok
    stuff['a'] = 4;  // error
    
    // ... or, if you're using this a lot and don't want to type so much ...
    interface StringMap { [key: string]: string; }
    var stuff2: StringMap = { };
    // same as above
    
    0 讨论(0)
提交回复
热议问题