xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript & Object Error

TypeScript & Object Error

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Object'.

Error


class StorageUtils {
  // [x: string]: Object;
  // key: string;;
  store: Object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  // string primitive
  getData(key: string = ``) {
    // this.store;
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
  // String Object
  // getData(key: String = ``) {
  //   // this.store;
  //   const obj = JSON.parse(sessionStorage.getItem(key));
  // }
  clear(key: string) {
    delete this.store[key];
  }
  clearAll() {
    this.store = {};
  }
  init() {
    this.store = {};
  }
}

https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b


OK

key keyof TypeObject

interface TypeObject {
  key: string;
}

class StorageUtils {
  // [x: string]: Object;
  store: TypeObject;
  constructor(store: TypeObject) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  // string primitive
  getData(key: string = ``) {
    // this.store;
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
  // String Object
  // getData(key: String = ``) {
  //   // this.store;
  //   const obj = JSON.parse(sessionStorage.getItem(key));
  // }
  clear(key: keyof TypeObject) {
    delete this.store[key];
  }
  clearAll() {
    this.store = {
      key: ``,
    };
  }
  init() {
    this.store = {
      key: ``,
    };
  }
}


TypeScript 2.1

keyof

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types


©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-02-15 16:46  xgqfrms  阅读(214)  评论(4编辑  收藏  举报