TypeScript - ts(7053) : Element implicitly has an 'any' type because expression of type 'string' can't be used to index

后端 未结 2 1493
予麋鹿
予麋鹿 2021-01-17 05:24

In TypeScript, I declare an interface like this:

export default interface MyDTO {
    readonly num: string;
    readonly entitle: string;
    readonly trb: st         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 05:57

    @mhodges, with your suggestions, here is my modified function which seems to work well. However in the following case, I had to add the "as string" otherwise I have the following error:

    Type 'string | keyof V 'cannot be used to index type' V'.ts (2536)

    public getDefaultComparator(property: keyof V | string, v1: V, v2: V): number {
        let compareReturn = 0;
        if (v1.hasOwnProperty(property)) {
          const compareValue1 = v1[property as string];
          const compareValue2 = v2[property as string];
          if (compareValue1 > compareValue2) {
            compareReturn = 1;
          } else if (compareValue1 < compareValue2) {
            compareReturn = -1;
          }
        }
    
        return compareReturn;
      }
    

提交回复
热议问题