TS2774

error TS2774: This condition will always return true since this function is always defined. Did you mean to call it instead?

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface MyDog {
age: () => number;
}

interface MyPerson {
name: string;
age: () => number;
}

function printAge(user: MyPerson | MyDog): void {
if (user.age) {

}
}

Fixed Code ✔️

Both interfaces (MyPerson & MyDog) declare a function named age, so that if-condition to check for its existence is unnecessary:

1
2
3
4
5
6
7
8
9
10
11
12
interface MyDog {
age: () => number;
}

interface MyPerson {
name: string;
age: () => number;
}

function printAge(user: MyPerson | MyDog): void {
console.log(user.age());
}