Flea Flea - 1 year ago 720
TypeScript Question

error TS7027: Unreachable code detected in Angular2 TypeScript Service class

I am following along with a PluralSight course and practicing writing a basic service in Angular2. I have the following service file:


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

export class CustomerService {

constructor() {}

getCustomers() {
{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'}

When I start up the lite-server using
npm start
I am receiving the following error:

angular-quickstart@1.0.0 start C:\Dev\my-proj
tsc && concurrently "tsc -w" "lite-server"

app/customer/customer.service.ts(10,3): error TS7027: Unreachable code detected.

When I comment out the return block, the lite-server starts fine, so it seems to be something in that return it does not like. Any help would be appreciated.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download