안녕하세요, typescript로 활성 루틴 및 리포지토리 논리를 구현하려고합니다. 그러나 제네릭 유형을 다루는 데 몇 가지 문제가 있습니다.
BaseModel
자체와 하위 유형을 반환하는 메서드를 만드는 추상 이 있습니다. 그렇게하기 위해 나는 그것이 돌아올 것이라고 말했다 BaseModel
. 에서 확장되는 제네릭 유형이있는 저장소에서 BaseModel
모델 메서드를 래핑하고 제네릭 유형을 반환 된 값으로 사용했습니다. 그러나 그렇게하면 오류가 발생합니다.
'BaseModel' is not assignable to type 'T'. 'BaseModel' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'BaseModel'.
내가 그것을봤을 때, 일반을 재 할당하거나 중첩 구조에서 복제 할 때 발생할 수있는 것과 같은 답변을 찾았습니다. 그러나 나는 무언가를 할당하거나 동일한 일반을 반복해서 정의하지 않습니다.
이 유형 오류가 발생하는 이유는 무엇이며 어떻게 해결합니까?
다음은 코드의 일부입니다.
BaseModel.ts
export abstract class BaseModel {
protected constructor(private attributes: any[] = []) {
}
create(attributes: any[] = null): BaseModel {
return this;
}
// ...
}
BaseRepository.ts
export class Repository<T extends BaseModel> {
constructor(private model: T) {
}
create(attributes: any[]): T {
return this.model.create(attributes);
}
// ...
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다