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

后端 未结 8 1720
旧时难觅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:47

    interface AccountSelectParams {
      ...
    }
    const params = { ... };
    
    const tmpParams: { [key in keyof AccountSelectParams]: any } | undefined = {};
      for (const key of Object.keys(params)) {
        const customKey = (key as keyof typeof params);
        if (key in params && params[customKey] && !this.state[customKey]) {
          tmpParams[customKey] = params[customKey];
        }
      }
    

    please commented if you get the idea of this concept

提交回复
热议问题