Imported function from js file, doesn't run in TS file - javascript

I'm trying to call a JS function inside a component in my TS file, but I'm getting an exception.
Component
import '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new GanttMaster();
}
}
Error:
Error referecences error: GanttMaster is not defined

You need to change the way you import the .js file:
import * as gantt from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new gantt.GanttMaster();
}
}
If you want to use GanttMaster among several components, you can import the .js file in angular.json and declare a constant in app.module.ts like declare const GanttMaster: any. Then you can use it in your application.
Hope this helps.
UPDATE
Alternatively, you can import it the way you've already done, but declare the function manually before the import:
declare const GanttMaster: any;
import from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new GanttMaster();
}
}
Ref: https://stackoverflow.com/a/37084553/1331040

In my project i load a js file from assets, something like this:
add this JavaScript file in scripts array in angular.json file like as above you have added jquery library.
"scripts": [
.....
"src/assets/js/custom.js"
]
custom.js:
function myTest() {
alert('Welcome to custom js');
}
You need declare in your component
declare const myTest: any;

Related

Instantiate a JavaScript object in TypeScript

I tried to instantiate a javascript object in a typescript file, basically in an Angular Application but there is an error as object is not defined.
My JavaScript file:
import { EventEmitter } from 'events';
export default class Cursor extends EventEmitter {
constructor(el) {}
//some methods
}
My typescript file
First alternative :
declare var Cursor:any;
export class HomeComponent implements OnInit {
ngOnInit(): void {
const cursor = new Cursor();
console.log(cursor.emit('enter'))
}
}
=> ERROR ReferenceError: Cursor is not defined
Second alternative (importing js file)
import Cursor from '../utils/js/cursor';
export class HomeComponent implements OnInit {
ngOnInit(): void {
const cursor = new Cursor();
console.log(cursor.emit('enter'))
}
}
=> Property 'emit' does not exist on type 'Cursor'.
In that case there is an inheritance problem with class Cursor extending EventEmitter
Can someone give me an hand with that problem ?
Thanks

axios property get of undefined

I have a class inside src/lib/lib.ts
export default class LibClass implements LibInterface {
someFunc () {
...
const httpResponse = await (this as any).$axios.$get(url)
return httpResponse.data
}
}
and inject it on the component via
import { Inject } from 'inversify-props'
import LibInterface from '#/lib/lib'
#Component
export default class Test extends Vue {
#Inject()
private libCLass!: LibInterface
}
and Im getting TypeError: Cannot read property '$get' of undefined
I already defined the #nuxtjs/axios on tsconfig.json
"types": [
"#nuxtjs/axios",
]
I used $axios on LibClass to be able to separate my axios calls and just call it on my components using dependency injection (inversify.js)
any idea on how can I fix this?

Typescript migration: Javascript "namespace" with multiple objects

I'm migrating some old js to ts. The file is of form (function implementations omitted for clarity):
// component.js
const Component = {}; // 'namespace' for components
Component.Base = function() {}
Component.A = function() {} // extends Base
Component.A.prototype.doStuffA = function() {}
Component.B = function() {} // extends Base
Component.B.prototype.doStuffB = function() {}
Component.C = function() {} // extends Base
// ... 100 other components, 2000 lines of code
export default Component;
In js, to use the file, I can do:
import Component from './component';
// 1. Instantiate one component
const compA = new Component.A();
// 2. or create multiple components
const threeComps = ['A', 'B', 'C'].map(name => new Component[name]() );
But in ts, I cannot even instantiate one component:
import Component from './component';
const compA: Component.A = new Component.A();
// tsc Cannot find namespace 'Component'
Question: What is the (quick) way to convert component.js into valid typescript, preferably keeping as many type-checks available as possible such
that
const compA: Component.A = new Component.B()
will be flagged as an error by the compiler.
I tried appending the following to the end of file:
namespace Component {
interface A {};
interface B {};
interface C {};
}
This seems to compile into correct javascript, but I would have to add all properties into interfaces. Seems tedious and violation of DRY-principle.
If you are going to migrate to TypeScript, you could immediately take advantage of the class syntax in your component.ts file:
export class Base {
}
export class A {
doStuffA() {}
}
export class B {
doStuffB() {}
}
export class C extends Base {
}
You can consume it using an import alias:
import * as Component from './component';
const a = new Component.A();
Or you can be selective with what you import:
import { A } from './component';
const a = new A();
Export Default / Modules Mixed With Namespaces
On the whole, the experts are saying that export default is a bad thing and that you shouldn't mix modules and namespaces.
You can do it, if you feel you must. here is the example with a namespace / default:
namespace Component {
export class Base {
}
export class A {
doStuffA() {}
}
export class B {
doStuffB() {}
}
export class C extends Base {
}
}
export default Component;
And the use:
import Component from './component';
const a = new Component.A();

Use JavaScript class in TypeScript

I have a problem introducing TypeScript to our JavaScript project.
First I want to use TypeScript only in my part of the code, leaving the JavaScript untouched.
Now I try to use a JavaScript class in my TypeScript code, but I don't find a solution in the last days.
The head of my TypeScript class with import of the JavaScript:
import { BaseLogic } from "../baseLogic";
export class ClaimLogic extends BaseLogic {
...
The JavaScript class ("baseLogic.js"):
module.exports = class BaseLogic {
constructor(meta, logger) {
...
My *.d.ts file ("baseLogic.d.ts"):
export class BaseLogic {
meta: any;
log: any;
constructor(meta: any, logger: any)
}
The head of the compiled JavaScript:
const baseLogic_1 = require("../baseLogic");
class ClaimLogic extends baseLogic_1.BaseLogic {
...
As you see in the compiled JavaScript baseLogic_1.BaseLogic is used.
This results in following error:
TypeError: Class extends value undefined is not a constructor or null
With only baseLogic_1 after the extends keyword in the JavaScript file all is fine.
I have no idea about a solution and hope you can help me!
Your import suppose to be import * as BaseLogic from "../baseLogic";.
In that way you will get the Class that you put on module.exports.
The codesnipet in baseLogic.js exports the class.
module.exports = class BaseLogic {
constructor(meta, logger) {
...
}
You try to access with class ClaimLogic extends baseLogic_1.BaseLogic an object that includes the class BaseLogic
Solution
import BaseLogic from '../baseLogic'
// or: const BaseLogic = require("../baseLogic");
class ClaimLogic extends BaseLogic {
...
}

Typescript module export not work when import something

I trying to create PowerBI custom visual and i must use typescript for that. I'm not too familiar with typescript. So I got 2 ts files under same namespace(I using VS Code editor):
visual.ts
module powerbi.extensibility.visual {
export class Visual implements IVisual {
private target: HTMLElement;
private updateCount: number;
constructor(options: VisualConstructorOptions) {
console.log('Visual constructor', options);
this.target = options.element;
this.updateCount = 0;
}
public update(options: VisualUpdateOptions) {
console.log('Visual update', options);
console.log(testFunc());
$('#datepicker').datepicker();
this.target.innerHTML = `<p>Update count: <em>${(this.updateCount++)}</em></p>`;
}
public destroy(): void {
//TODO: Perform any cleanup tasks here
}
}
}
test.ts
import React=require('react');
import ReactDOM=require('react-dom');
module powerbi.extensibility.visual {
export function testFunc():String{
return "Test string";
}
export class TestClass{}
}
Problem is when there is no imports in test.ts i can see and use exported function "testFunc()"(VS Code see that function) but when i add imports i cant user that function(also VS Code don't recognize that function)? Is there any way to have imports and to use that function?

Categories