使用pnpm遇到的一个小bug
使用pnpm遇到的一个小bug
推荐阅读:(这期强烈推荐)
问题
在使用 pnpm 包管理工具,进行 tsc 编译时,
遇到错误:error TS2742:
The inferred type of 'Subclass' cannot be named without a reference to '../middle/node_modules/types/lib'. This is likely not portable. A type annotation is necessary.
github 上对应 issue
和 solution
:
环境
node:v18.17.1
pnpm:8.6.12
typescript:4.6.4
解决方式
下面的解决方式只是 issue 47663 中的一种,里面也还有其他的解决方式。
一个很小的复现:ts-indirect-type-reference-bug
在 consumer 包导入下面代码即可:
import type {} from "types";
代码展示
package consumer
import { createBaseClass } from "middle";
import type {} from "types";
// this will trigger an error
// index.ts:3:14 - error TS2742: The inferred type of 'Subclass' cannot be named without
// a reference to '../middle/node_modules/types/lib'. This is likely not portable. A type annotation is necessary.
export class Subclass extends createBaseClass() {}
package middle
import { Class } from "types";
export interface Counter {
count: () => number;
}
export const createBaseClass = (): Class<Counter> => {
return class implements Counter {
private counter = 0;
public count() {
return ++this.counter;
}
};
};
package types
export interface Class<TInterface, TArgs extends Array<unknown> = never> {
new (...args: TArgs): TInterface;
}