Property Existence Checks with in
What you'll learn: How to use the in operator to safely narrow unknown types by checking if specific properties exist before accessing them.
The Property Detective Pattern
When you receive data typed as unknown (like parsed JSON or user input), TypeScript won't let you access any properties — it has no idea what shape the value has. The in operator becomes your property detective, checking whether a property exists on an object before TypeScript allows you to use it.
How the in Operator Works with unknown
The in operator checks if a property name exists in an object at runtime. When TypeScript sees you use in with an unknown value, it narrows the type based on whether the check succeeds:
function processData(input: unknown) {
// Before narrowing: can't access anything
// input.name; // Error!
if (typeof input === "object" && input !== null) {
// Now we know it's an object, but still can't access properties
if ("name" in input) {
// TypeScript now knows: input is an object WITH a 'name' property
console.log(input.name); // Safe!
}
if ("age" in input && "name" in input) {
// Both properties confirmed
console.log(`${input.name} is ${input.age} years old`);
}
}
}
The Two-Step Dance
Notice the pattern: first check it's an object (and not null), then use in to check for specific properties. This two-step approach ensures you're checking property existence on something that can actually have properties.
function handleResponse(response: unknown) {
if (typeof response === "object" && response !== null) {
if ("success" in response && "data" in response) {
console.log("Got successful response with data");
} else if ("error" in response) {
console.log("Got error response");
}
}
}
Key Takeaway: The in operator lets you check if properties exist on unknown objects, narrowing the type so TypeScript allows property access. Always verify you have an object first with typeof and a null check before using in.