반응형
가변 인수 개수가있는 함수에 대한 TypeScript 유형 서명
가변 양의 인수를 허용하는 함수 멤버로 인터페이스를 정의하는 데 문제가 있습니다. 다음 개체 리터럴을 예로 들어 보겠습니다.
var obj = {
func: () => {
for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
};
다음과 같은 인터페이스를 정의하고 싶습니다.
interface IExample {
func: ( ??? ) => void;
}
따라서 다음 코드는 오류없이 컴파일 할 수 있습니다.
var test = (o: IExample) {
o.func("a");
o.func("a", "b");
o.func("a", "b", "c");
...
}
TypeScript는 ECMAScript 6 스프레드 제안을 사용합니다.
하지만 유형 주석을 추가하면 다음과 같습니다.
interface Example {
func(...args: any[]): void;
}
척의 대답에 추가하기 위해 인터페이스를 정의 할 필요가 없습니다. ...
메서드 에서 직접 수행 할 수 있습니다 .
class Header { constructor(public name: string, public value: string) {} }
getHeaders(...additionalHeaders: Header[]): HttpHeaders {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json')
if (additionalHeaders && additionalHeaders.length)
for (var header of additionalHeaders)
headers.append(header.name, header.value);
return headers;
}
그런 다음 호출 할 수 있습니다.
headers: this.getHeaders(new Header('X-Auth-Token', this.getToken()))
또는
headers: this.getHeaders(new Header('X-Auth-Token', this.getToken()), new Header('Something', "Else"))
... args [] 인수가 사용되지 않는 경우 Typescript는 여전히 Javascript에 배열을 만들고 여기에 인수를 복사합니다.
To avoid this unnecessariness you can make a prototype for the function as well as the function, thus:-
function format_n(str: string, ... $n: any[]): string;
function format_n(str: string): string {
return str.replace(/%(\d+)/g, (_, n) => format_n.arguments[n]);
}
반응형
'IT story' 카테고리의 다른 글
Task의 예외는 Task에서 Waiting 또는 Exception 속성에 액세스하여 관찰되지 않았습니다. (0) | 2020.08.26 |
---|---|
데이터 URL에서 캔버스로 이미지 그리기 (0) | 2020.08.26 |
matplotlib 컬러 맵을 적용하여 Numpy 배열을 PIL 이미지로 변환하는 방법 (0) | 2020.08.26 |
C ++ 사용자 입력 대기 (0) | 2020.08.26 |
SASS에서 다른 파일의 클래스에서 상속 할 수 있습니까? (0) | 2020.08.26 |