Type 'CrazyClass' provides no match for the signature 'new (): { hello: number; }'

今天看TypeScript Deep Dive的时候有个例子

interface Crazy {
    new(): {
        hello: number;
    };
}

class CrazyClass implements Crazy {
    constructor() {
        return { hello: 123 };
    }
}

// Because
const crazy = new CrazyClass(); // crazy would be { hello:123 }

编译的时候会报错 Type ‘CrazyClass’ provides no match for the signature ‘new (): { hello: number; }’
这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。下面对构造函数进行类型检查。

// 构造方法使用
interface Crazy {
    new(): {
        hello: number;
    };
}

// 类使用
interface CrazyClassInterface {
    hello: number;
}


class CrazyClass implements CrazyClassInterface {
    hello: number;
    constructor() {
        this.hello = 123;
    }
}

function ct1(ct: Crazy) {
    return new ct();
}

let obj = ct1(CrazyClass);
console.log(obj);

修改为以上代码,Crazy接口修改为构造函数使用,类实现CrazyClassInterface接口也存在构造函数约束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值