banner
SlhwSR

SlhwSR

热爱技术的一名全栈开发者
github
bilibili

ts typeof inference implicit type and application scenarios

Use Case 1#

Assume a function that takes two parameters, obj and key.

function getObj(obj: object, key: string) {
  return obj[key]
}

The problem is that key may not be a valid index on obj, so there is a risk.
Therefore, it is necessary to assert key as a type on obj, as follows.

function getObj(obj: object, key: string) {
  return obj[key as keyof typeof obj]
}

Of course, you can also do it like this.

function getObj<T>(obj: object, key: keyof T): T[keyof T] {
  return obj[key]
}

Use Case 2#

Assume the backend passes a constraint to define global user information.

const getInfo = async () => {
  const res = await fetch("/auth/all")
  const value = await res.json()
  type C = Partial<typeof value[0]>
}

Manipulate the C type as needed.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.