zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript 4.9] 'in' operator

typescript in &# 39 Operator 4.9
2023-09-14 08:59:11 时间

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
}