[Typescript] Scopes and TypeParams

When working with function parameters, we know that “inner scopes” have the ability to access “outer scopes” but not vice versa

function receiveFruitBasket(bowl) {
  console.log("Thanks for the fruit basket!")
  // only `bowl` can be accessed here
  eatApple(bowl, (apple) => {
    // both `bowl` and `apple` can be accessed here
  })
}

 

Type params work a similar way:

// outer function
function tupleCreator<T>(first: T) {
  // inner function
  return function finish<S>(last: S): [T, S] {
    return [first, last]
  }
}
const finishTuple = tupleCreator(3)
// const t1: [number, null]
const t1 = finishTuple(null)
// const t2: [number, number[]]
const t2 = finishTuple([4, 8, 15, 16, 23, 42])

 

posted @ 2022-08-08 17:59  Zhentiw  阅读(31)  评论(0编辑  收藏  举报