1

I want to add custom methods to my class definitions in Angular 2. But I get errors like the following when I try to then create mock objects (see the Angular 2 Tour of Heroes tutorial).

public/app/mock-searches.ts(3,14): error TS2322: Type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...' is not assignable to type 'Search[]'.
  Type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...' is not assignable to type 'Search'.
    Property 'refreshProducts' is missing in type '{ box: { x: number; y: number; width: number; height: number; }; dateCreated: Date; eventIdStr: s...'.
public/app/search.service.ts(33,40): error TS2304: Cannot find name 'err'.

refreshProducts(): void is a method declared for the Search class I'm trying to mock. How can I best resolve this error? Or am I trying to do something backwards, that may handled in a more conventional way in Angular 2?

search.ts (sample)

import { Rect } from './rect';

export class Search {
  box: Rect;
  dateCreated: Date;
  products: Product[];

  refreshProducts(): void {
    // Do something useful
  }
}

mock-searches.js (sample)

import { Search } from './search';

export const SEARCHES: Search[] = [
  { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  }
];
Marty Chang
  • 6,269
  • 5
  • 16
  • 25

1 Answers1

2

If your object literals don't conform to the class structure, then you can just "cast" it (or maybe more precisely type assertion)

export const SEARCHES: Search[] = [
  <Search> { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  },
  <Search> { 
    box: { x: 4, y: 4, width: 20, height: 20 },
    dateCreated: new Date(),
    products: []
  }
];

You just need to make sure that whatever is using the mocks, doesn't actually need to use the refreshProducts() method of the mock Search

See Also:

  • This post which explains a bit about TypeSript's structural type system
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720