programing

유형 스크립트 클래스: "오버로드 서명이 함수 구현과 호환되지 않습니다."

javajsp 2023. 7. 3. 22:35

유형 스크립트 클래스: "오버로드 서명이 함수 구현과 호환되지 않습니다."

다음 클래스를 만들었습니다.

export class MyItem {
  public name: string;
  public surname: string;
  public category: string;
  public address: string;

  constructor();
  constructor(name:string, surname: string, category: string, address?: string);
  constructor(name:string, surname: string, category: string, address?: string) {
    this.name = name;
    this.surname = surname;
    this.category = category;
    this.address = address;
  }
}

다음 오류가 발생합니다.

오버로드 서명이 함수 구현과 호환되지 않습니다.

생성자를 오버로드하기 위해 여러 가지 방법을 시도했는데, 마지막으로 시도한 방법은 위에 올린 것입니다(여기서 얻는 것).

하지만 여전히 같은 오류가 발생합니다.내 코드에 무슨 문제가 있습니까?

구현 함수의 서명이 선언한 빈 생성자를 만족하지 않기 때문에 컴파일 오류가 발생합니다.
기본 생성자를 사용하려면 다음과 같이 해야 합니다.

class MyItem {
    public name: string;
    public surname: string;
    public category: string;
    public address: string;

    constructor();
    constructor(name:string, surname: string, category: string, address?: string);
    constructor(name?: string, surname?: string, category?: string, address?: string) {
        this.name = name;
        this.surname = surname;
        this.category = category;
        this.address = address;
    }
}

(플레이그라운드의 코드)

실제 구현의 모든 인수는 선택 사항이며 기본 생성자에 인수가 없기 때문입니다.
이러한 방식으로 구현 함수는 다른 두 서명을 모두 만족하는 서명을 가집니다.

그러나 다른 두 개를 선언할 필요 없이 단일 서명만 사용할 수 있습니다.

class MyItem {
    public name: string;
    public surname: string;
    public category: string;
    public address: string;

    constructor(name?: string, surname?: string, category?: string, address?: string) {
        this.name = name;
        this.surname = surname;
        this.category = category;
        this.address = address;
    }
}

(플레이그라운드의 코드)

이 둘은 동등합니다.

언급URL : https://stackoverflow.com/questions/39407311/typescript-class-overload-signature-is-not-compatible-with-function-implementa