[Typescript 4.9] 'in' operator

Before version 4.9, you will get type error for the code:

interface Context {
  packageJSON: unknown
}

function tryGetPackageName(context: Context) {
  const packageJSON = context.packageJSON
  if (packageJSON && typeof packageJSON === "object") {
    if ('name' in packageJSON) {
      return packageJSON.name
    }
  }
}

 

With v4.9 update, code works as expected.

And also packageJSONgot type as const packageJSON: object & Record<"name", unknown>

We can restrict it even further:

interface Context {
  packageJSON: unknown
}

function tryGetPackageName(context: Context): string | undefined{
  const packageJSON = context.packageJSON
  if (packageJSON && typeof packageJSON === "object") {
    if ('name' in packageJSON && typeof packageJSON.name === "string") {
      return packageJSON.name
    } 
  }

  return undefined
}

 

posted @ 2022-11-30 15:15  Zhentiw  阅读(21)  评论(0编辑  收藏  举报