繁体   English   中英

在打字稿中对对象数组进行排序-元素隐含具有任何类型

[英]Sort array of objects in typescript - element implicty has any type

我正在尝试对函数中的对象数组进行排序,但是该函数将键作为参数接收,所以它是未知的:

export interface ProductsList {
   id: boolean
   nome: string
   qtde: number
   valor: number
   valorTotal: number
}

const exampleFn = (productsData: ProductsList[], order: string) => {
   if (order !== 'id' && order !== 'nome') {
        productsData.sort((a, b) => b[order] - a[order])
   }
}

我收到order错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProductsList'.
  No index signature with a parameter of type 'string' was found on type 'ProductsList'

我尝试将index signature设置为order ,但没有成功。

会是什么?

由于减去字符串或布尔值没有意义,您应该使用keyofexclude

export interface ProductsList {
   id: boolean
   nome: string
   qtde: number
   valor: number
   valorTotal: number
}

const exampleFn = (productsData: ProductsList[], order: Exclude<keyof ProductsList, 'id'| 'nome'>) => {
   productsData.sort((a, b) => {
       const c = a[order]
       return b[order] - a[order]
       })
}

编辑:通过密钥检查,您也可以跳过exclude

const exampleFn = (productsData: ProductsList[], order: keyof ProductsList) => {
   if (order !== 'id' && order !== 'nome') {
      productsData.sort((a, b) => {
         const c = a[order]
         return b[order] - a[order]
      })
   }
}

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM