The in operator narrowing in Typescript - Time & Space Complexity
We want to see how using the in operator affects the time it takes for a program to run.
Specifically, how checking if a property exists in an object changes the work done as input grows.
Analyze the time complexity of the following code snippet.
function process(input: object, keys: string[]) {
for (const key of keys) {
if (key in input) {
console.log(`Found key: ${key}`);
}
}
}
This code checks each key in an array to see if it exists in the given object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the
keysarray and checkingkey in input. - How many times: Once for each key in the
keysarray.
Each key check takes about the same time, so total work grows as the number of keys grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 property checks |
| 100 | About 100 property checks |
| 1000 | About 1000 property checks |
Pattern observation: The work increases directly with the number of keys checked.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the number of keys grows.
[X] Wrong: "Checking if a key exists with in takes longer for bigger objects."
[OK] Correct: Property checks with in are very fast and do not depend on object size because objects use fast lookup methods internally.
Understanding how property checks scale helps you reason about code efficiency and write better programs.
"What if we replaced the object with a nested object and checked keys deeply? How would the time complexity change?"
Practice
What does the in operator do in TypeScript?
Solution
Step 1: Understand the
Theinoperator purposeinoperator checks if a given property exists in an object.Step 2: Recognize its use in TypeScript narrowing
TypeScript uses this check to narrow the type safely based on the presence of the property.Final Answer:
Checks if a property exists in an object and narrows the type -> Option BQuick Check:
inoperator = property check and type narrowing [OK]
in checks property presence to narrow types [OK]- Thinking
inadds or deletes properties - Confusing
inwith equality checks - Assuming
inworks only for arrays
Which of the following is the correct syntax to check if property name exists in object obj using the in operator?
?
Solution
Step 1: Recall the
The correct syntax is:inoperator syntax"propertyName" in object.Step 2: Match the syntax with options
"name" in obj matches the correct syntax exactly:"name" in obj.Final Answer:
"name" in obj -> Option AQuick Check:
Syntax is "property" in object [OK]
- Reversing the order of property and object
- Using method calls instead of
in - Leaving
inwithout operands
What will be the output of the following TypeScript code?
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
return "Fish can swim";
} else {
return "Bird can fly";
}
}
console.log(move({ swim: () => {} }));Solution
Step 1: Analyze the input object
The object passed has aswimmethod, so it matches theFishtype.Step 2: Check the
The conditioninoperator condition"swim" in animalis true, so the function returns "Fish can swim".Final Answer:
"Fish can swim" -> Option CQuick Check:
Property "swim" exists, so output is "Fish can swim" [OK]
- Confusing which property belongs to which type
- Assuming both properties exist simultaneously
- Expecting compile or runtime errors
Identify the error in this TypeScript code using the in operator and fix it:
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(animal: Cat | Dog) {
if (animal in "meow") {
return "Cat speaks";
} else {
return "Dog speaks";
}
}Solution
Step 1: Check
The syntax requires the property name as the left operand and the object as the right operand.inoperator syntaxStep 2: Identify the error in the code
The code usesanimal in "meow", which reverses operands. It should be"meow" in animal.Final Answer:
Theinoperator operands are reversed; should be "meow" in animal -> Option AQuick Check:
Property name must be left, object right inin[OK]
- Swapping operands of the
inoperator - Using
typeofinstead ofinfor property checks - Ignoring TypeScript narrowing benefits
Given the following types and function, what will describeAnimal return when called with { fly: () => {}, name: "Eagle" }?
type Fish = { swim: () => void };
type Bird = { fly: () => void; name: string };
function describeAnimal(animal: Fish | Bird) {
if ("swim" in animal) {
return "Fish";
} else if ("name" in animal) {
return `Bird named ${animal.name}`;
} else {
return "Unknown";
}
}Solution
Step 1: Check the input object properties
The object hasflyandnameproperties, but noswim.Step 2: Evaluate the
First conditioninoperator conditions"swim" in animalis false. Second condition"name" in animalis true, so it returnsBird named Eagle.Final Answer:
"Bird named Eagle" -> Option DQuick Check:
Property "name" exists, so output is "Bird named Eagle" [OK]
- Assuming presence of
flymeans Fish - Ignoring the second
incheck forname - Expecting errors due to missing
swim
Ready to prove it?
Pass the test and this pattern moves unknown
