typescripttypescript2.9

Typescript: How to get typechecking while mapping over a list


Im using Typescript 2.9.1. Example of my problem:

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'
}))

I understand that Typescript can't determine the type as it is returned in the callback function. But what is the least verbose way of getting good type checking?


Solution

  • [].map is designed to allow you to change the type, so it doesn't know your intent is to return MyType. You can tell it:

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