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 packageJSON
got 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