[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 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
}
相关文章
- [Typescript 4.9] TypeScript 4.9: satisfies operator
- [Typescript] Tips: Use 'in' operator to transform a union to another union(watched)
- [Typescript] Make your optional fields required in TypeScript
- [Typescript] Generics using TypeScript
- [TypeScript] Union Types and Type Aliases in TypeScript
- [TypeScript] Function Overloads in Typescript
- [Typescript] Generics in a Class Names Creator
- [Typescript] Use Generics in a Reduce Function
- [Typescript] Zod in action
- [Typescript] Exclude Properties from a Type in TypeScript (Omit)
- [TypeScript] Make Properties and Index Signatures Readonly in TypeScript
- [TypeScript] Using Interfaces to Describe Types in TypeScript