source

일반 형식 스크립트를 사용하여 인터페이스 확장

nicesource 2023. 6. 13. 22:24
반응형

일반 형식 스크립트를 사용하여 인터페이스 확장

저는 어떤 개체든 사용할 수 있는 함수를 만들고 싶고 추가된 속성이 거의 없는 개체를 반환하고 싶습니다.다음과 같은 것:

    //this code doesn't work   
        function addProperties<T>(object: T): IPropertiesToAdd<T> {/*implmentions code*/};

        interface IPropertiesToAdd<T> extend T{
            on(): void;
            off(): void;
        }

//usage example
var str = new String('Hello')
addProperties(str)
str.charAt(3)
str.on() 

위의 코드 형식 스크립트 컴파일러의 경우 인터페이스가 클래스 또는 인터페이스만 추가할 수 있다는 오류를 반환합니다. 이 오류를 형식 스크립트로 표현하려면 어떻게 해야 합니까?

개체가 다른 개체 유형의 기능을 상속할 수 있는 새 유형 별칭을 만들 수 있습니다.여기서 이 코드를 찾았습니다.

type IPropertiesToAdd<T extends {}> = T & {    // '{}' can be replaced with 'any'
    on(): void
    off(): void
};

interface ISomething {
    someValue: number
}

var extendedType: IPropertiesToAdd<ISomething> = {
    on(): void {
        console.log("switched on");
    },
    off(): void {
        console.log("switched off");
    },
    someValue: 1234,
};

제가 이것을 테스트해봤는데, 'T'는 인터페이스, 클래스, 배열 유형이 될 수 있는 것 같습니다.저는 조합 유형을 일할 수 없었습니다.

익명 개체에서만 작동하며 실제 상속 용도로는 사용할 수 없습니다.

이게 도움이 되길 바랍니다.

인터페이스IPropertiesToAdd이름이 지정된 인터페이스를 확장하는 데 사용되는 유형 변수 T를 정의합니다.T이것은 불가능합니다.인터페이스는 변수 이름을 사용하여 참조할 수 없습니다. 고정 이름을 가져야 합니다(예: Evnt:

interface Evnt<T> {
  name: T;
}

interface IPropertiesToAdd<T> extends Evnt<T> {
  on(): void;
  off(): void;
}

저는 당신의 경우에 당신이 무엇을 성취하려고 하는지 확신할 수 없습니다.예제를 조금 확장했으므로 다음과 같이 컴파일됩니다.

function addProperties<T>(object: Evnt<T>): IPropertiesToAdd<T> {
  /* minimum implementation to comply with interface*/
  var ext:any = {};
  ext.name = object.name
  ext.on = function() {};
  ext.off = function() {};
  return ext;
};

interface Evnt<T> {
  name: T;
}

interface IPropertiesToAdd<T> extends Evnt<T> {
  on(): void;
  off(): void;
}

//usage example
var str = {name: 'Hello'}
var evnt = addProperties(str)
evnt.charAt(3); // error because evnt is not of type 
                // `string` but `IPropertiesToAdd<string>`
evnt.on()

문제 해결 방법:

type IModelProperty<T = Record<string, any>> = T & {
     on(): void;
     off(): void;
};

언급URL : https://stackoverflow.com/questions/26652179/extending-interface-with-generic-in-typescript

반응형