error TS7027: Unreachable code detected in Angular2 TypeScript Service class

If you place your whole array in a new line after the return statement, then your method has two statements:

  • return undefined
  • an array definition

The error you see is a pretty helpful one. TypeScript tells you that there is code (the array definition) that could never be reached, because you are returning from the function already before the array line can be reached.

So the solution is pretty simple. Move at least the opening bracket into the line of the return statement like return [. That's it.


I tweaked it a bit. This should work:

import {Injectable} from "@angular/core";

@Injectable()
export class CustomerService
{
    private data: Array<any>;

    constructor()
    {
        this.data = [
            {id: 1, name: 'Ward'},
            {id: 2, name: 'Joe'},
            {id: 3, name: 'Bill'},
            {id: 4, name: 'Bob'},
            {id: 5, name: 'Levi'},
            {id: 6, name: 'Brian'},
            {id: 7, name: 'Susie'}
        ];
    }

    getCustomers()
    {
        return this.data;
    }
}

or if you want the original the new array needs to start on the same line:

import {Injectable} from "@angular/core";

@Injectable()
export class CustomerService
{

    constructor()
    {
    }

    getCustomers()
    {
        return [
            {id: 1, name: 'Ward'},
            {id: 2, name: 'Joe'},
            {id: 3, name: 'Bill'},
            {id: 4, name: 'Bob'},
            {id: 5, name: 'Levi'},
            {id: 6, name: 'Brian'},
            {id: 7, name: 'Susie'}
        ];
    }
}