如何在typescript中将空字符串转换为null?

x6h2sr28  于 2022-11-30  发布在  TypeScript
关注(0)|答案(1)|浏览(200)

我是打字的新手,我已经绕了很久了
我有两个接口,一个是从数据库读取,我无法控制它,也不能相信它返回的值是我期望的值。

// pulled from database
interface JobTableRow {
  job_number: string,
  description: string | null,
  project_manager: string | null,
  status: string | null,
  ts_customer_id: string | null,
  completed_date: string | null,
  date_stamp: string,
  time_stamp: string,
  contract_base: number,
  contract_approved_changes: number,
  contract_revised_total: number,
  jtd_cost: number,
  start_date: string | null,
  labor_tax_group: string | null,
  material_tax_group: string | null,
  subcontract_tax_group: string | null,
  equipment_tax_group: string | null,
  overhead_tax_group: string | null,
  other_tax_group: string | null,
  ts_row_id: string,
  ts_row_version: string
}
// manually calculated field after being pulled from the database
interface JobMapping extends JobTableRow {
  ts_updated: string
}

示例记录:

const mapped: JobMapping = {
  job_number: '0000',
  description: 'some project',
  project_manager: 'some person',
  status: 'active',
  date_stamp: '2020-04-20',
  time_stamp: '11:12:57',
  labor_tax_group: '',
  material_tax_group: '',
  subcontract_tax_group: '',
  equipment_tax_group: '',
  overhead_tax_group: '',
  other_tax_group: '',
  // ...
  ts_updated: '2020-04-20T18:12:57.000Z'
}

我习惯在nodejs中这样做,以便将空字符串值转换为null,但是typescript对我大喊Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'JobMapping'. No index signature with a parameter of type 'string' was found on type 'JobMapping'.ts(7053)

Object.keys(mapped).forEach(key => {
  if (typeof mapped[key] === 'string') {
    let val: string = mapped[key]
    if (val === '') mapped[key] = null
  }
})
yeotifhr

yeotifhr1#

您可以通过执行以下操作来修复错误:

let mapped: JobMapping = {
  job_number: '0000',
  description: 'some project',
  project_manager: 'some person',
  status: 'active',
  date_stamp: '2020-04-20',
  time_stamp: '11:12:57',
  labor_tax_group: '',
  material_tax_group: '',
  subcontract_tax_group: '',
  equipment_tax_group: '',
  overhead_tax_group: '',
  other_tax_group: '',
  // ...
  ts_updated: '2020-04-20T18:12:57.000Z'
}

Object.keys(mapped).forEach(key => {
  const keyWithType = key as keyof typeof mapped;
  let value = mapped[keyWithType];
  if (typeof value === 'string' && value === "") {
    mapped = {...mapped, [keyWithType]: null};
  }
})

相关问题