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: []
  }
];

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.