Tìm kiếm trang web

Khai báo một lớp trong TypeScript với tất cả các thuộc tính của một kiểu đối tượng hiện có


Một cấu trúc phổ biến mà tôi sử dụng trong TS là lấy một định nghĩa đối tượng JSON thuần và biến nó thành một lớp khi chạy. Ví dụ:

export type LessonDef = {
  id: string
  title: string
  slug: string
  shortdesc: string
  explanation: string
  exercises: {
    from: string
    message: string
    translation: string
    hint?: string
    feedback?: { [key: string]: string }
  }[]
}

export class Lesson {
  constructor(readonly def: LessonDef) {
    Object.assign(this, def)
  }

  // Additional methods go here
}

Vấn đề là hệ thống kiểu không hiểu kết quả của Object.assign. Làm thế nào tôi có thể nói với TypeScript rằng Lesson mở rộng kiểu của LessonDef?

Câu trả lời #1

Vui lòng xem câu trả lời liên quan

Bạn có thể hợp nhất khai báo lớp và giao diện của mình.

Hãy xem xét ví dụ này:

interface Lesson {
    id: string
    title: string
    slug: string
    shortdesc: string
    explanation: string
    exercises: {
        from: string
        message: string
        translation: string
        hint?: string
        feedback?: { [key: string]: string }
    }[]
}

declare let x: Lesson;

class Lesson {
    constructor(def: Lesson) {
        Object.assign(this, def);
    }
}

const result = new Lesson(x)

result.exercises // ok

Sân chơi

@Cerberus cảm ơn bạn đã chỉ ra lỗi của tôi liên quan đến việc sử dụng {... def} thay vì def

Tuy nhiên, có một nhược điểm, bạn có thể tham khảo this.exercises trước Object.assign

class Lesson {
    constructor(def: Lesson) {
        this.exercises //ok, <----- DRAWBACK!
        Object.assign(this, def);
    }
}