Typescript:在编译时使用“ for”而不是许多重复的语句吗?

时间:2018-07-01 18:58:18

标签: typescript

有两个接口,一个具有一些可选属性,而另一个则没有:

interface ISTATE {
  events?: {
    [key in HookName]?: EventFunc
  },
  transitions?: {
    [transName: string]: TransFuncStr
  },
  store?: {
    [key: string]: any
  }
}

interface IVALIDSTATE {
  name: string
  events: {
    [key in HookName]?: EventFunc
  },
  transitions: {
    [transName: string]: TransFuncStr
  },
  store: {
    [key: string]: any
  }
}

我想将ISTATE转换为IVALIDSTATE。对于ISTATE中的每个属性,我必须检查它是否存在,并将值复制到IVALIDSTATE对象:

function resolveStates(iStates: { [name: string]: ISTATE }): { [name: string]: IVALIDSTATE } {
  const ret: { [name: string]: IVALIDSTATE } = {}
  for (const i in iStates) {
    ret[i] = {} as IVALIDSTATE
    ret[i].name = i

    if (!iStates[i].events) {
      ret[i].events = {}
    } else {
      ret[i].events = iStates[i].events as any
    }

    if (!iStates[i].transitions) {
      // same if statement like'events'
    }

    if (!iStates[i].store) {
      // same if statement like'events'
    }
  }
  return ret
}
  1. 重复的if (!iStates[i].property) {}语句过多,我可以使用for ... in语句代替许多重复的语句吗? (因为... in需要运行时,所以keyof可以做到吗?)
  2. 有没有更简单的方法将可选属性转换为非可选属性?现在,我必须使用as any以避免类型检查。

1 个答案:

答案 0 :(得分:2)

所以,也许您正在寻找类似的东西:

ret[i] = {} as IVALIDSTATE
ret[i].name = i
// new stuff below
const keys: (keyof ISTATE)[] = ['events','transitions','store'];        
keys.forEach(k => {
  const iStateK = iStates[i][k]; 
  ret[i][k] = iStateK || {};
});

要点:

希望有帮助。祝你好运!