Web3.js: Cannot use 'new' with an expression whose type lacks a call or construct signature

Created on 25 Mar 2018  路  5Comments  路  Source: ChainSafe/web3.js

A issue in thethis.web3 = new Web3(window.web3.currentProvider); the web3.js has output and I type to the code of console.log(window.web3.currentProvider) that window.web3.currentProvider is defined. But the terminal occurs issue like as fellow:

ERROR in src/app/app.service.ts(36,20): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Environment:
system:Ubuntu16.04
web.js:"1.0.0-beta.33"

screenshot from 2018-03-25 15-34-06

I import the web3.js like that : import * as Web3 from 'web3';

Most helpful comment

What I ended up doing to stop typescript from complaining and still have type definition and autocompletion is

import * as W3 from 'web3';
const Web3 = require('web3'); // tslint:disable-line

const web3: W3.default = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
const balance = await web3.eth.getBalance('0x...');
...

All 5 comments

Web3.js unfortunately doesn't use ES Modules, so you can't import it like that. You have to require it like it's 2010 :)

Thank you ! @macbem. First I use Web3.js in .ts file ,so invoking this module in require it will occur issue like error TS2304: Cannot find name 'require'. .Second, I try to it through import { default as Web3 } from 'web3'; ,but the issue prompt the default_web3.js is undefined. Last, the same code and the same code work normally in another computer .I don't know what the problem is ?

As i said before, Web3.js doesn't use ES Modules, so you can't use default imports - you have to use require and it requires some changes in TypeScript config - look it up on Stack Overflow, it's pretty trivial to implement.

Thank you! @macbem I try to do it ,why it's useful for others that use the ES Modules? Can you tell me the reason? And I don't know where the TypeScript config should be modified? the tutorial I don't know where have?

What I ended up doing to stop typescript from complaining and still have type definition and autocompletion is

import * as W3 from 'web3';
const Web3 = require('web3'); // tslint:disable-line

const web3: W3.default = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
const balance = await web3.eth.getBalance('0x...');
...
Was this page helpful?
0 / 5 - 0 ratings