Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface based programming with TypeScript, Angular 2 & SystemJS

I'm currently trying to clean up some code in order to program against interfaces rather than against implementations but can't figure out how to.

To be more specific, I'm using: * TypeScript 1.5.0 beta -> transpiled to ES5 / commonjs * SystemJS to load the modules

I currently try to use external modules as follows:

posts.service.ts file:

///<reference path="../../../typings/tsd.d.ts" />
///<reference path="../../../typings/typescriptApp.d.ts" />
...
export interface PostsService{ // 1
    fetchPosts(): Rx.Observable<any>;
}
export var PostsService:PostsServiceImpl; // 2
...
export class PostsServiceImpl implements PostsService { // 3
    ...
    constructor(){
        console.log('Loading the Posts service');
}
...
fetchPosts(): Rx.Observable<any>{ 
   ...
}

and that module is imported in posts.ts:

    ///<reference path="../../../typings/tsd.d.ts" />
    ///<reference path="../../../typings/typescriptApp.d.ts" />

    import {PostsService, PostsServiceImpl} from 'components/posts/posts.service';

    @Component({
    selector: 'posts',
    viewInjector: [
        //PostsServiceImpl
        //PostsService
        bind(PostsService).toClass(PostsServiceImpl)
    ]
})
...
export class Posts {
    private postsServices: PostsService;

    constructor(postsService: PostsService) {
        console.log('Loading the Posts component');
        this.postsServices = postsService;
        ...
    }

    ...
}

The above code compiles correctly, but basically my issue boils down to the fact that Angular won't inject an instance of PostsServiceImpl in the Posts component.

Of course it's simply because I don't find the correct way to declare/export/import everything

Without export interface PostsService ..., I get TS compilation errors because I use it in the posts controller.

Without export var PostsService:PostsServiceImpl; I get TS compilation errors in the @View decorator's viewInjector

In the generated js code I only find exports.PostsService; which is added because of the export var... I know that interfaces disappear at runtime.

So I'm a bit lost in all this. Any practical ideas how I can use interface based programming w/ TypeScript & Angular 2?

like image 592
dSebastien Avatar asked Jul 03 '15 08:07

dSebastien


1 Answers

Any practical ideas how I can use interface based programming w/ TypeScript & Angular 2

Interfaces are erased at runtime. In fact decorators don't support interfaces either. So you are better off using something that does exist at runtime (i.e. implementations).

like image 62
basarat Avatar answered Oct 26 '22 10:10

basarat