区块链开发遇TS2339报错:类型'() => WordArray'无substring属性
报错原因
- 构造函数初始化属性错误:你在构造函数中写了
this.hash = this.calculateHash,这里是把calculateHash函数本身赋值给了hash属性,而不是函数执行后的返回结果,初始状态下hash是函数类型,后续逻辑里又会把哈希计算结果赋值给hash,导致hash的类型混乱,调用方式不一致。 - SHA256返回值类型不匹配:你使用的SHA256方法(通常来自crypto-js类库)返回的是
WordArray类型对象,不是原生字符串,本身没有substring字符串方法,直接调用会触发类型报错。 - 挖矿逻辑的调用方式错误:
mineBlock方法的while循环中,你调用了this.hash(),但后续循环里你已经把this.hash赋值为哈希计算结果,不是函数,执行到第二次循环就会触发调用报错。
解决方法
需要修改3处代码:
- 构造函数中
this.hash的初始赋值改为调用calculateHash的返回结果 calculateHash方法中,将SHA256的返回值转为字符串mineBlock的循环判断中,直接读取this.hash属性即可,不需要加括号调用
修改后的完整代码如下(如果是JavaScript项目,删掉类型标注即可运行):
import SHA256 from 'crypto-js/sha256'; // 未引入类库的话需要先加这行 class Block { index: number; timestamp: string | number; data: any; previousHash: string; hash: string; nonce: number; constructor(index: number, timestamp: string | number, data: any, previousHash = ''){ this.index = index; this.timestamp = timestamp; this.data = data; this.previousHash = previousHash; // 修改点1:执行函数拿到初始哈希值,而非赋值函数本身 this.hash = this.calculateHash(); this.nonce = 0; } calculateHash(){ // 修改点2:将SHA256返回的WordArray转为字符串 return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString()).toString(); } mineBlock(difficulty: number){ // 修改点3:直接读取hash属性,不需要加括号调用 while(this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")){ this.nonce++; this.hash = this.calculateHash(); } console.log("Block mined: " + this.hash); } }
内容的提问来源于stack exchange,提问作者Koala
相关产品推荐
相关产品推荐

