Why am I getting TS2345 error by directive definition?

I am trying to port an existing angular application to typescript (version 1.5.3):

Here is the code:

'use strict'; angular.module('x') .directive('tabsPane', TabsPane) function TabsPane(itemTabs) { return { restrict: 'E', compile: compileTabs }; function compileTabs(tElement) { var template = createTabsTemplate(); //function which i don't include here for brevity tElement.append(template); }} 

When I compile javascript, I get:

error TS2345: argument of type '(itemTabs: any) => {restrict: string; compile: (tElement: any) => void; } 'is not assigned to a parameter of type "any []". The 'push' property is not in the type '(itemTabs: any) => {restrict: string; compile: (tElement: any) => void; } ".

I tried to understand why he complains about this, I came to the definition of typescript angular:

Somehow typescript implies this definition

directive (name: string, inlineAnnotatedFunction: any []): IModule;

where the following definition would be more appropriate:

directive (name: string, directiveFactory: IDirectiveFactory): IModule;

I am completely new to typescript, so I assume that I am doing something wrong, but I cannot find anything related to google.

+6
source share
3 answers

When compiling in a directive, it should always return something, so in this case a simple return true; added at the bottom of your compilation function will solve your problems.

+2
source

I faced the same problem when porting from old javascript angularJs 1.4.9 code to typescript 2.6 code. I am using @ types / angular ver 1.6.39. I added "any" as the return type of the parameter function, for example:

  angular.module("app") .directive("tabsPane", function TabsPane(itemTabs): any { return { restrict: 'E', compile: compileTabs }; function compileTabs(tElement) { var template = createTabsTemplate(); tElement.append(template); } }); 

The error has disappeared :)

+2
source

Perhaps you need to update the version of angular.d.ts, as in the latest version I can see:

directive (name: string, directiveFactory: IDirectiveFactory): IModule;

which will give something like: .directive('myCustomer', function(){...} after compilation

Near:

directive (name: string, inlineAnnotatedFunction: any []): IModule;

which will give something like .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {...} after compilation (it actually changed to this commit , but it was a mistake in for a long time)

Edit (since you seem to have the latest version of angular.d.ts)

Try specifying the return type of your function using this syntax:

var TabsPane = (itemTabs) : ng.IDirectiveFactory => {}

+1
source

All Articles