首页 > 其他分享 >[Typescript 4.9] 'in' operator

[Typescript 4.9] 'in' operator

时间:2022-11-30 15:25:04浏览次数:55  
标签:context Typescript const name 4.9 Context operator packageJSON

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
}

 

标签:context,Typescript,const,name,4.9,Context,operator,packageJSON
From: https://www.cnblogs.com/Answer1215/p/16938554.html

相关文章