JS Built-ins
TypeScriptintermediate

Type Guard β€” hasProperty

πŸ“– Usage Example
function hasProperty<K extends string>(x: unknown, key: K): x is Record<K, unknown> {
  return typeof x === 'object' && x !== null && key in x
}
hasProperty({ name: 'Alice' }, 'name')   // β†’ true

The 'in' operator checks property existence, narrowing to Record<K, unknown> in TypeScript.

Type Guards: hasProperty

Challenge: Implement hasProperty<K extends string>(obj: unknown, key: K): obj is Record<K, unknown> β€” returning true if obj is a non-null object that has the given key.

hasProperty({ name: 'Alice' }, 'name')  // β†’ true
hasProperty({ name: 'Alice' }, 'age')   // β†’ false
πŸ’‘ Hints (1)
  • β€’ Combine a null check with the in operator.