วิธีการละเว้นข้อผิดพลาด TypeScript "Type instantiation is excessively deep and possibly infinite. ts(2589)"?
หลังจากอัปเดตเป็น Typescript 3.5 ฉันได้รับข้อผิดพลาด "การสร้างอินสแตนซ์ประเภทมีความลึกมากเกินไปและอาจไม่มีที่สิ้นสุด (2589)" จำนวนมาก
ฉันจะเพิกเฉยต่อพวกเขาได้อย่างไร?
ที่โค้ดเกิดขึ้น (ใช้ TypeORM)
import { Connection, Repository, Entity, BaseEntity, createConnection } from 'typeorm';
@Entity()
class MyEntity extends BaseEntity {
public id: number;
}
class Test {
async test() {
const connection: Connection = await createConnection();
const repo1 = connection.getRepository(MyEntity);
const repo2: Repository<MyEntity> = connection.getRepository(MyEntity); // only here cast the error above
}
}
ฉันสังเกตว่ามีเพียงการเริ่มต้น repo2 เท่านั้นที่ทำให้เกิดข้อความแสดงข้อผิดพลาด
คำตอบ #1
ฉันสามารถทำให้ข้อผิดพลาดหายไปได้ในขณะที่ยังสามารถคำนวณประเภทได้อย่างถูกต้องด้วยการใช้ @ts-ignore ตัวอย่างสามารถพบได้ใน playground โดยสรุปหากคุณลบ // @ts-ignore ในสภาพแวดล้อมการพัฒนาที่ครบถ้วน ฉันจินตนาการว่าโค้ดจะไม่สามารถคอมไพล์ได้
คำตอบ #2
... คุณควรเห็นข้อผิดพลาด:
type Test00<T1 extends any[], T2 extends any[]> =
Reverse<Cast<Reverse<T1>, any[]>, T2>
การสร้างตัวอย่างชนิดมีความลึกเกินไปและอาจเป็นอนันต์ ts(2589)
สิ่งนี้เกิดขึ้นเมื่อ TS ตัดสินว่าประเภทนั้นซับซ้อนเกินไปที่จะคำนวณ (เช่น). วิธีแก้ไขคือการคำนวณประเภทที่ก่อปัญหาเป็นขั้นตอน:
type Test01<T1 extends any[], T2 extends any[]> =
Reverse<Reverse<T1> extends infer R ? Cast<R, any[]> : never, T2>
https://github.com/microsoft/TypeScript/issues/30188#issuecomment-478938437
