简体   繁体   English

从数组的 object 中排序键的值,该键是 typescript 中的可选类型?

[英]sort value of key from object of array that key is optional type in typescript?

What is the best practice for me to sort an object of array by value of key that key is optional type from Object?对我来说,按键值对数组的 object 进行排序的最佳做法是,该键是 Object 中的可选类型? I have following code that works if num is not optional type However, I got error that Object is possibly 'undefined'.如果 num 不是可选类型,我有以下代码可以工作但是,我收到Object is possibly 'undefined'.

type Filter = {
    a: number;
    num?: number

}
const filter: Filter[] = [{a: 1, num: 10}, {a: 1, num: 12}, {a: 1, num: 5}]
filter.sort((a,b)=> (a.num > b.num ? 1 : -1))
console.log(filter)

2 options come to my mind:我想到了2个选项:

  1. The obvious one: use a type where num is not optional.显而易见的:使用num不是可选的类型。 You can use the Required utility type if you do not want to keep both types without rewriting the properties.如果不想在不重写属性的情况下保留这两种类型,则可以使用Required实用程序类型。

  2. If you cannot change the type, that probably means you really want that property to be optional.如果您无法更改类型,这可能意味着您确实希望该属性是可选的。 So you simply should check for it in your sort function.因此,您只需在您的排序 function 中检查它。 You need to check if num is undefined and decide what to return when that occurs.您需要检查num是否undefined并决定在发生这种情况时返回什么。 When you check it, Typescript will infer everything that falls out of that condition will be defined.当您检查它时,Typescript 将推断出所有不属于该条件的内容都将被定义。 For instance:例如:


filter.sort((a,b)=> {
  if (typeof a.num === 'undefined' || typeof b.num === 'undefined') {
    return 0;
  }
  return (a.num > b.num ? 1 : -1)
})

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

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