代码之家  ›  专栏  ›  技术社区  ›  pgsandstrom

Typescript:如何在映射列表时进行类型检查

  •  1
  • pgsandstrom  · 技术社区  · 6 年前

    type MyType = {
      replaceThisProp: string
    }
    
    const instance:MyType = {
      replaceThisProp: 'hello',
    }
    
    const instanceList:MyType[] = [instance]
    
    // Misspelling the property here causes an error:
    const updatedInstance:MyType = {
        ...instance,
        replaceThisPropp:'Oops'
    }
    
    // But here no error is given:
    const result: MyType[] = instanceList.map<MyType>(h =>({
      ...h,
      replaceThisPropp:'Oops'
    }))
    

    我知道Typescript无法确定类型,因为它是在回调函数中返回的。但是,什么是最不冗长的方式获得良好的类型检查?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Madara's Ghost    6 年前

    [].map 它的设计允许您更改类型,因此它不知道您的意图是返回 MyType . 你可以告诉它:

    const result = instanceList.map((h): MyType =>({
      ...h,
      replaceThisPropp:'Oops' // now errors.
    }))