ค้นหาเว็บไซต์

typescript - ข้อผิดพลาดประเภททั่วไป TS2322: ประเภท '{ id: null; }' ไม่สามารถกำหนดค่าให้กับประเภท 'T' ได้


ฉันกำลังได้รับข้อผิดพลาดการตรวจสอบประเภท TS ในโค้ดด้านล่างนี้

interface Resource {
  id: string;
}

interface ResourceState<T> {
  data: T;
  hash: string;
}

abstract class ResourceComponent<R extends Resource> {
  protected state: ResourceState<R> = {
    data: { // Type checking KO
      id: ''
    },
    hash: ''
  };
}

// Doesn't suit my use case
// abstract class ResourceComponent<Resource> {
//   protected state: ResourceState<Resource> = {
//     data: {
//       id: null
//     },
//     hash: ''
//   };
// }

interface Model extends Resource {
  name: string;
}

class ModelComponent extends ResourceComponent<Model> {
  constructor() {
    super();
    this.state.data.name = 'ModelComponent'; // Type checking OK
    this.state.data.age = 20; // Type checking OK
    console.log(this.state.data);
  }
}

const component = new ModelComponent();

ในบรรทัดที่ 12 อย่างแม่นยำ ฉันได้รับข้อผิดพลาด TS2322: Type '{ id: null; }' ไม่สามารถกำหนดค่าให้กับ type 'R' ได้ TypeScript ไม่ควรเข้าใจบ้างหรือว่าเนื่องจาก 'R extends Resource' ข้อมูลสามารถถูกเริ่มต้นด้วยค่าที่มีรูปแบบของ Resource Type

ในบรรทัดที่ 36, 37 TS ตรวจสอบชนิดข้อมูลได้อย่างถูกต้อง

https://stackblitz.com/edit/typescript-rthmqv

คำตอบ #1

คุณต้องบอกวัตถุข้อมูลของคุณว่าสิ่งที่คุณกำลังมอบหมายให้กับมันจริงๆ แล้วคือ R

abstract class ResourceComponent<R extends Resource> {
  protected state: ResourceState<R> = {
    data : { // Type checking KO
      id: "null"
    } as R,
    hash: ''
  };
}