返回

typescript-一组唯一的有序键值对,其中键仅为另一种类型的有效键

发布时间:2022-04-20 15:31:21 179

我想创建一个类型,它接受一个集合(一个包含非重复键的键/值对的数组)。

// I have any given interface:
interface PersonRecord {
  id: string
  name: string
  age: number
}

// A type for order by direction
type SortDirection = "asc" | "desc"

我希望有一些类型/接口组合,可以让我这样做:

有效对象:

const orderSort: SortType = {
  0: { id: "asc" }
  1: { age: "desc" }
}

const personNameSort: SortType = {
  0: { name: "desc" }
}

// only one key from PersonRecord at a time can be used in
// the values of the top level keys
const orderSort: SortType = {
  0: { id: "asc", age: "desc" }
}

// The top level keys must be numbers starting at zero and iterating
// every natural number by having no skips
const orderSort: SortType = {
  0: { id: "asc" }
  2: { age: "desc" }
}

// "xxx" is not a valid value because its not "asc" or "desc"
const personNameSort: SortType = {
  0: { name: "xxx" }
}

// test is not a key on PersonRecord
const personNameSort: SortType = {
  0: { test: "xxx" }
}

// keys from PersonRecord can only be used once
const orderSort: SortType = {
  0: { id: "asc" }
  1: { id: "desc" }
}

type SortType = { [K in keyof Partial]: SortDirection }

我会接受一些替代解决方案:一个键/值数组(值限制为“asc”或“desc”)钥匙不能重复使用:

// this would work...
const sortOrder = [{name: "asc"},{age: "desc"}]

// ...but this wouldn't because age was already included in the array.
// If there's not a clean way of adding this restriction, then I can
// write code to prevent this restriction programmatically I'm sure.
const sortOrder = [{name: "asc"},{age: "desc"},{age: "asc"}]

编辑:因此,为了帮助解决这个问题,让我解释一下它的用途。

我想做一个这样的函数:

// orderArgs could be an array also so maybe something like
// SortType[] and each item in the array is just something like:
// [{someAttribute: "asc"},{anotherAttribute: "desc"}]
// and you can only have an array of ONE key/value pair.
const orderBy = (orderArgs: SortType) => {
  // a variable that orderBy has access to is called
  // 'records' which is of type: T[]
  return records.sort((last, next) => {
    // to determine which value to return (-1, 0 or 1)
    // I want to sort against the first item in orderArgs
    // if they are not equal, return 1 or -1.
    // However, if they are equal, go to the next item in
    // orderArgs and try sort based on that.
    // If you've gone through the whole list of orderArgs,
    // then last and next are truly equal, so return 0 here.
  }
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
相关帖子