我如何在打字稿中输入这个对象?

我的对象看起来像这样:

 const searchOptions: any = {
      fullText: 'hifi',
      'brand.id': [1,2,3,4],
      'category.id': [1,2,3,4],
      'country.id': [1,2,3,4],
      'property.id': [1,2,3,4],
    }

这非常方便,因为 API 接受相同的查询参数。

我如何在 TypeScript 中输入这个对象?

回答

对于 typescript 4.1 或更高版本,您可以使用Key Remapping

type Props = 'brand' | 'category' | 'country' | 'property'

type Base = {
  fullText: string
}

type Obj = {
  [Prop in Props as `${Prop}.id`]: number[]
} & Base

const searchOptions: Obj = {
  fullText: 'hifi',
  'brand.id': [1, 2, 3, 4],
  'category.id': [1, 2, 3, 4],
  'country.id': [1, 2, 3, 4],
  'property.id': [1, 2, 3, 4],
}

如果这些 props'brand' | 'category' | 'country' | 'property'是某个对象的键,你可以keyof SomeObj用来检索它们


以上是我如何在打字稿中输入这个对象?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>