打字稿:映射类型中的可选参数

时间:2021-06-08 16:25:49

标签: typescript types

我正在尝试使用一些必需参数和一些可选参数来实现映射类型。

以下代码适用于必需参数,但我不能使用可选参数。

type Foo = { foo: string }

const A_FIELD_REQ = ['x', 'y'] as const
const A_FIELD_OPT = ['z'] as const

const B_FIELD_REQ = ['x', 'y', 'z'] as const
const B_FIELD_OPT = [] as const

type QueryA = {
  type: 'a'
  fields: { [field in typeof A_FIELD_REQ[number]]: Foo | undefined }
}

type QueryB = {
  type: 'b'
  fields: { [field in typeof B_FIELD_REQ[number]]: Foo | undefined }
}

type Query = {
  id: string
} & (QueryA | QueryB)

const myQueries: Query[] = [
  {
    id: '0',
    type: 'a',
    fields: {
      x: { foo: '' },
      y: { foo: '' },
    },
  },
  {
    id: '1',
    type: 'a',
    fields: {
      x: undefined, // valid
      y: { foo: '' },
    },
  },
  {
    id: '2',
    type: 'b',
    fields: {
      x: { foo: '' },
      y: { foo: '' },
      z: { foo: '' },
    },
  },
]

我想如何使用我的类型

我应该能够处理与我的 fields 类型相同的键 Query 中的可选参数。与基本的 z?: Foo | undefined 完全一样。

const myQueries = [
  {
    id: '0',
    type: 'a',
    fields: {
      x: { foo: '' },
      y: { foo: '' },
    },
  },
  {
    id: '1',
    type: 'a',
    fields: {
      x: undefined, // valid
      y: { foo: '' },
    },
  },
  {
    id: '2',
    type: 'b',
    fields: {
      x: { foo: '' },
      y: { foo: '' },
      z: { foo: '' },
    },
  },
  {
    id: '3',
    type: 'a',
    fields: {
      x: { foo: '' },
      y: { foo: '' },
      z: { foo: '' }, // !!! optional parameter !!!
    }
  }
]

1 个答案:

答案 0 :(得分:0)

只需添加 ? 可选修饰符

type QueryA = {
  type: 'a'
  fields: { [field in typeof A_FIELD_REQ[number]]?: Foo }
}

type QueryB = {
  type: 'b'
  fields: { [field in typeof B_FIELD_REQ[number]]?: Foo }
}