xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub! TypeScript & Object Error TypeScript 2.1

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

xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
TypeScript  & Object Error
TypeScript 2.1

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://*.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 发布文章使用:只允许注册用户才可以访问!