'Why is this snippet invalid TypeScript?

Consider the following TypeScript snippet:

function containsWord(): boolean {
    const fullText: string[] = ['This is a sentence with seven words'];
    const word: string = 'word';

    return (
        fullText.reduce((acc, sentence) => acc && sentence.includes(word), true)
    );
}

console.log(containsWord())

When trying to compile this snippet in VS Code or in the TypeScript playground, I get the following error:

Type 'string' is not assignable to type 'boolean'

Which I don't really understand. What's really surprising is that moving the content of the return statement to a variable fixes the issue:

function containsWord(): boolean {
    const fullText: string[] = ['This is a sentence with seven words'];
    const word: string = 'word';

    const result = fullText.reduce((acc, sentence) => acc && sentence.includes(word), true);

    return result;
}

console.log(containsWord());

Or explicitly setting the callback arguments types:

function containsWord(): boolean {
    const fullText: string[] = ['This is a sentence with seven words'];
    const word: string = 'word';

    return (
        fullText.reduce((acc: boolean, sentence: string) => acc && sentence.includes(word), true)
    );
}

console.log(containsWord());

I'm very confused by the fact that the first snippet is invalid while the two others are fine according to TypeScript. It looks like type inference is somehow failing in the first snippet. Shouldn't they all be equivalent?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source