[英]Sort array of objects in typescript - element implicty has any type
I'm trying to sort an array of objects within a function, however the function receives the key as a parameter, so it's unknown:我正在尝试对函数中的对象数组进行排序,但是该函数将键作为参数接收,所以它是未知的:
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])
}
}
I'm getting this error with 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'
I've tried to set an index signature
to order
, but without success.我尝试将
index signature
设置为order
,但没有成功。
What can it be?会是什么?
Since substracting string or boolean makes no sense, you should use keyof
and an exclude
:由于减去字符串或布尔值没有意义,您应该使用
keyof
和exclude
:
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]
})
}
edit : With the key check, you can also skip the exclude
!编辑:通过密钥检查,您也可以跳过
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.