typescript 类型的打印脚本Map

lh80um4z  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(203)

调用具有任何作为主体传递的api函数,需要转换为类型,但带有条件
使用的类型为

export type aircraft = {
   _id?: ObjectId,
   groupid: ObjectId,
   reg: string,
   type?: string,
   desc?: string,
   arc?: Date,
 }

有没有更好的方法来做这件事?

export function addAircraft(newAircraft: any) {

  const insertAircraft: aircraft = {
    reg: newAircraft.reg,
    groupid: new ObjectId(newAircraft.groupid),
    type: newAircraft.type,
    desc: newAircraft.desc,
    arc: new Date(newAircraft.arc)
  }
}

我不希望newAircraft中缺少的任何字段出现在insertAircraft中
我已经看过object.entries,但有点迷失,因为我看的是输入对象,而不是目标对象
已尝试生成上述result_id,因此没有问题
示例:

newAircraft = {
    reg: G-ABCD,
    groupid: '',
    desc: 'Test Description',
 }

结果

insertAircraft = {
    reg: G-ABCD,
    groupid: '',
    type: null,
    desc: 'Test Description',
    arc : null
 }

所以在上面的字段arc和type是null,我不希望它在那里。

insertAircraft = {
    reg: G-ABCD,
    groupid: '',
    desc: 'Test Description'
 }

如果还有日期类型,需要根据函数转换为日期

rekjcdws

rekjcdws1#

所以我现在得到了正确的结果,可能不是最好的编码

export function convertToAircraft(aircraft: any) {

let retval = new Map()

const dateType = [ 'arc', 'annual']
const objectType = [ '_id', 'groupid']

for (const [k, v] of (Object.entries(aircraft) as unknown as [string, any][])) {
    let newval: any

    if (dateType.includes(k)) { newval = new Date(v); }
    else
        if (objectType.includes(k)) { newval = new ObjectId(v); }
        else
            {
                newval = v
            }
    
    retval.set(k,newval)
    
}
const newAircraft: aircraft = Object.fromEntries(retval)

return newAircraft
}

但是提供了我需要的结果,我现在可以添加类型,它会将类型转换为ObjectId或Date

相关问题