【问题标题】:why do i get error TS2345 on directive definition?为什么我在指令定义上收到错误 TS2345?
【发布时间】:2015-11-20 17:59:10
【问题描述】:

我尝试将现有的 Angular 应用迁移到 typescript(1.5.3 版):

代码如下:

  '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);
        }}

当我编译 javascript 我得到:

错误 TS2345: 类型参数 '(itemTabs: any) => { restrict: string;编译: (tElement: any) => void; }' 不能分配给“any[]”类型的参数。 类型 '(itemTabs: any) => { restrict: string; 中缺少属性 'push'编译: (tElement: any) => void; }'。

我试图理解为什么它在这里抱怨我去了 angular 的 typescript 定义:

打字稿不知何故暗示了这个定义

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

以下定义更合适:

directive(名称:字符串,directiveFactory:IDirectiveFactory):IModule;

我对 typescript 完全陌生,所以我认为我做错了什么,但我找不到任何与 google 相关的内容。

【问题讨论】:

  • 晚了但是:在我的情况下,需要刷新一些挥之不去的缓存。对我来说解决方案有点老套,但我将返回类型设置为:void 保存了文件,然后删除了返回类型并再次保存。瞧,没有更多错误了。

标签: angularjs typescript typescript1.5


【解决方案1】:

我在从旧的 javascript angularJs 1.4.9 代码迁移到 typescript 2.6 代码时遇到了同样的问题。我正在使用@types/angular 版本 1.6.39。我添加了“任何”作为参数函数的返回类型,例如:

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

            function compileTabs(tElement) {
                var template = createTabsTemplate();
                tElement.append(template);
            }
       });

错误消失了:)

【讨论】:

    【解决方案2】:

    在指令中运行 compile 时,它​​必须始终返回一些内容,因此在这种情况下,添加到 compile 函数底部的简单 return true; 将解决您的问题。

    【讨论】:

      【解决方案3】:

      也许你必须更新你的 angular.d.ts 版本,因为在 the latest 我可以看到:

      directive(名称:字符串,directiveFactory:IDirectiveFactory):IModule;

      编译后会给出类似:.directive('myCustomer', function(){...}

      就在:

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

      编译后会给出类似.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {...}的东西 (其实在this commit改了,不过一直是个bug)

      编辑(因为您似乎拥有最新版本的 angular.d.ts)

      尝试使用以下语法指示函数的返回类型:

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

      【讨论】:

      • 我已经有最后一个版本了。我在 tsd 文件中有两个定义,但打字稿假定我想要第一个版本
      • 指令定义有问题。当我将 Idirective 从 compile?: IDirectiveCompileFn 更改为 compile?: any;问题解决了
      • 你试过吗:var TabsPane = (itemTabs) : IDirectiveFactory => {}
      • 尝试此操作时,我得到:错误 TS2304:找不到名称“IDirectiveFactory”。
      • 对不起ng.IDirectiveFactory ?
      猜你喜欢
      • 2020-09-28
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多