제네릭 클래스 인스턴스가 주어진 인터페이스에 맞도록 강제하는 제약 조건을 만드는 방법은 무엇입니까?

다니엘 산

이 코드가 있습니다.

interface Class {
    new(...args: any[]): any;
}

class Wrapper<C extends Class> {
    asInterface<InstanceType<C> extends I>(): I { // this is where the constraint should go
        return undefined as any as I; // this is not important
    }
}

interface Plane {
    takeoff(): void;
}

interface Car {
    drive(): void;
}

class F35B {
    takeoff() {
        console.log('doing vertical takeoff');
    }
    shoot() {
        console.log('bang bang');
    }
}

const w = new Wrapper<typeof F35B>();
const plane = w.asInterface<Plane>(); // this should pass
const car = w.asInterface<Car>(); // this should not

생성자 C 인스턴스의 확장이되도록 asInterface 메서드에 대한 제약 조건을 어떻게 설정할 수 있습니까?

물론 표현 InstanceType<C> extends I은 타이프 스크립트와 호환되지 않지만 그것이 질문의 핵심 아이디어입니다.

다니엘 산

나는 삼항 유형 표현식을 사용하면 다음과 같이 반환 유형에서 제한 될 수 있음을 알았습니다.

interface Class {
    new(...args: any[]): any;
}

type Subtype<I, C extends Class> = InstanceType<C> extends I ? I : never;


class Wrapper<C extends Class> {
    asInterface<I>(): InstanceType<C> extends I ? I : never { // The constraint is the resulting expression
        // @ts-ignore
        return undefined; // this is not important
    }
}

interface Plane {
    takeoff(): void;
}

interface Car {
    drive(): void;
}

class F35B {
    takeoff() {
        console.log('doing vertical takeoff');
    }
    shoot() {
        console.log('bang bang');
    }
}

const w = new Wrapper<typeof F35B>();
const plane = w.asInterface<Plane>();
plane.takeoff();
const car = w.asInterface<Car>();
car.takeoff();
//  ^^^^^^^ Property 'takeoff' does not exists on type never

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관