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接口也存在构造函数约束。

在 Vue 中,当遇到错误信息 **Type 'string[]' provides no match for the signature '(): IterableIterator<any>'**,这通常出现在试图将一个 `string[]` 型的数组赋值给某个期望返回 `IterableIterator<any>` 型的属性或方法时。这种情况常见于 Vue 组件的 props 或响应式数据定义中型不匹配的问题。 ### 错误原因分析 该错误的本质是型不兼容,具体来说: - `string[]` 是一个字符串数组型。 - `(): IterableIterator<any>` 表示一个返回 `IterableIterator` 型的函数,例如 `function(): IterableIterator<any>`。 - TypeScript 认为这两个型不具备兼容性,因为它们的签名结构完全不同。 例如,以下代码可能触发此错误: ```typescript interface MyComponentProps { items: () => IterableIterator<any>; } export default defineComponent({ props: { items: { type: Function as PropType<() => IterableIterator<any>>, required: true } }, setup(props) { const list = ['item1', 'item2', 'item3']; props.items = () => list; // ❌ 错误:Type 'string[]' is not assignable to type '() => IterableIterator<any>' } }); ``` ### 解决方案 要解决这个问题,可以通过以下几种方式之一进行修复: #### 1. 修改数据传递方式 确保传递的是一个函数,而不是直接赋值数组: ```typescript props.items = function* () { yield* ['item1', 'item2', 'item3']; }; ``` 这里使用了生成器函数 `function*`,它天然返回一个 `IterableIterator`。 #### 2. 显式转换数组为可迭代对象 如果目标接受的是可迭代对象,可以使用 `Symbol.iterator` 显式包装数组: ```typescript props.items = () => ['item1', 'item2', 'item3'][Symbol.iterator](); ``` #### 3. 调整型定义 如果实际使用中不需要 `IterableIterator`,而是只需要数组,可以调整接口或 prop 的型定义: ```typescript interface MyComponentProps { items: string[]; } export default defineComponent({ props: { items: { type: Array as PropType<string[]>, required: true } }, setup(props) { console.log(props.items); // ✅ 正确:items 是 string[] } }); ``` #### 4. 使用 TypeScript 型断言(谨慎使用) 在确认数据结构兼容的情况下,可以使用型断言绕过型检查: ```typescript props.items = () => ['item1', 'item2', 'item3'] as any; ``` 但建议仅在开发调试时使用,不推荐在生产代码中广泛使用型断言。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值