【问题标题】:Importing a default namespace - why am I getting "undefined"?导入默认命名空间 - 为什么我得到“未定义”?
【发布时间】:2018-08-10 20:21:40
【问题描述】:

我尝试学习打字稿 - 迈出第一步 :)。这是我的问题。

我创建 File1.ts 如下:

export namespace ex {
    export var mapper = ( ob : Object ) : NewClass {
        return ob as NewClass;
    };

    export class NewClass extends Object {
        public getSomething() : number {
            return 2;
        }
    };
}

然后,我创建了 File2.ts,它使用了第一个文件中定义的“映射器”:

import { ex } from './Ex';

var a : Object = myAlreadyExistingObject;
console.log( ex.mapper( a ).getSomething() );

我得到了什么:

错误:TypeError:File1_1.ex.mapper(a).getSomething 不是函数。

“Object”类只是一个例子——实际上我使用的是一个已经定义的复杂类。我想要实现的是在 C# 中使用“扩展方法”,像这样使用它:ex.mapper( instance ).newFunction()

为什么它不起作用?

【问题讨论】:

  • 忘记添加 - 错误提示它是“不是函数,而是未定义”

标签: typescript cocoscreator


【解决方案1】:
return ob as NewClass;

TypeScript 中的类型断言不会导致运行时更改。如果ob之前没有getSomething方法,那么这个函数的返回值也不会,你会得到描述的错误。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2013-06-04
    • 1970-01-01
    • 2016-05-12
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2014-08-10
    相关资源
    最近更新 更多