// TypeScript: Type 'string' is not assignable to type 'User'
// At runtime: callers get a string instead of an object
function getUserById(id, users) {
const user = users.find(u => u.id === id);
if (!user) return null;
// Bug: returns user.name (string) instead of user (object)
return user.name;
}
const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin' },
{ id: 2, name: 'Bob', email: 'bob@example.com', role: 'user' },
];
const result = getUserById(1, users);
// Caller expects an object with .email, but gets a string
const email = result && typeof result === 'object' ? result.email : 'not found';
const name = result && typeof result === 'object' ? result.name : result;
console.log(name);
console.log(email);function getUserById(id, users) {
const user = users.find(u => u.id === id);
if (!user) return null;
// Fix: return the full user object
return user;
}
const users = [
{ id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin' },
{ id: 2, name: 'Bob', email: 'bob@example.com', role: 'user' },
];
const result = getUserById(1, users);
const email = result ? result.email : 'not found';
const name = result ? result.name : 'not found';
console.log(name);
console.log(email);Bug: getUserById returns user.name (string) instead of user (object). TypeScript would catch this with a return type annotation. Callers cannot access .email because they receive a string.
Explanation: Returning the full user object allows callers to access all properties. TypeScript enforces return type consistency — if you annotate the return type as User, returning a string would be a compile error.
Key Insight: Always annotate function return types in TypeScript: function getUserById(id: number): User | null. This catches accidental narrowing bugs where you return part of an object instead of the whole thing.