我有一个可以使用 JavaScript 的插件。我想在 AngularJS2 中使用 TypeScript 组件内部的函数。我用过各种方法都没有成功。
@angular/cli: 1.0.0-rc.0, node: 7.7.2, @angular/core: 2.4.9
假设我想使用以下函数cube.js:
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export default { cube, foo };
使用类型定义方法,我创建了cube.d.ts,如下所示:
interface Cube {
cube(x:number):number;
}
export default Cube;
在我的组件中,我导入了如下函数:
import Cube from './cube';
...
public myCube:Cube;
console.log(myCube.cube(3));
但它给了我以下错误:
Error in :0:0 caused by: Cannot read property 'cube' of undefined TypeError: Cannot read property 'cube' of undefined at HComponent.webpackJsonp
在 tsconfig.json 中,allowJS 为 true(编辑:“allowJs”:true)。 @type 模块已经安装。仍然无法读取简单的 JS 函数。
有什么想法吗?
最佳答案
我找到了答案。
我的cube.js 文件:
"use strict";
class Cube {
cube(x) {
return x * x * x;
}
}
export default Cube;
我的cube.d.ts文件
export default class Cube {
cube(x: number): number;
}
在 ts 组件中,我有:
/// <reference path="./cube.d.ts" />
import Cube from './cube';
...
const my = new Cube();
console.log(my.cube(10));
关于javascript - 在 TypeScript 和 AngularJS 2 中导入 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42906991/