itsource

TypeScript에서 문자열을 수락하고 문자열을 반환하는 함수 배열을 선언하려면 어떻게 해야 합니까?

mycopycode 2023. 6. 16. 21:42
반응형

TypeScript에서 문자열을 수락하고 문자열을 반환하는 함수 배열을 선언하려면 어떻게 해야 합니까?

업데이트 - 이 질문의 맥락은 TypeScript 1.4 이전입니다.그 버전 이후로, 저의 첫 번째 추측은 언어에 의해 뒷받침되었습니다.답변에 대한 업데이트를 참조하십시오.


단언할 수 있습니다f문자열을 받아들이고 문자열을 반환하는 함수가 됨:

var f : (string) => string

그리고 나는 선언할 수 있습니다.g문자열 배열이 될 경우:

var g : string[]

어떻게 선언할 수 있습니까?h"문자열을 받아들이고 문자열을 반환하는 함수"의 배열이 될 것인가요?

내 첫 번째 추측은:

var h : ((string) => string)[]

그것은 구문 오류인 것 같습니다.추가 괄호를 제거하면 문자열에서 문자열 배열까지의 함수가 됩니다.

난 이해했다.문제는 그것이=>함수 유형 리터럴은 그 자체가 구문 설탕일 뿐이며 작곡을 원하지 않습니다.[].

사양에 명시된 대로:

폼의 함수 형식 리터럴입니다.

( ParamList ) => 반환 유형

객체 유형 리터럴과 정확히 일치합니다.

(ParamList ) : 반환 유형 }

그래서 제가 원하는 것은:

var h : { (s: string): string; }[]

전체 예:

var f : (string) => string

f = x => '(' + x + ')';

var h : { (s: string): string; }[]

h = [];

h.push(f);

업데이트:

변경 세트로 판단하면 1.4의 형식 선언에서 괄호가 허용되므로 질문의 "첫 번째 추측"도 정확할 것입니다.

var h: ((string) => string)[]

추가 업데이트 1.4에 있습니다!

당신의 연구를 바탕으로 저는 작은 클래스의 플래닛 그리터/Say Hello:'를 썼습니다.

/* PlanetGreeter */

class PlanetGreeter {
    hello    : { () : void; } [] = [];
    planet_1 : string = "World";
    planet_2 : string = "Mars";
    planet_3 : string = "Venus";
    planet_4 : string = "Uranus";
    planet_5 : string = "Pluto";
    constructor() {
        this.hello.push( () => { this.greet(this.planet_1); } );
        this.hello.push( () => { this.greet(this.planet_2); } );
        this.hello.push( () => { this.greet(this.planet_3); } );
        this.hello.push( () => { this.greet(this.planet_4); } );
        this.hello.push( () => { this.greet(this.planet_5); } );
    } 
    greet(a: string): void { alert("Hello " + a); }
    greetRandomPlanet():void { 
        this.hello [ Math.floor( 5 * Math.random() ) ] (); 
    } 
} 
new PlanetGreeter().greetRandomPlanet();

언급URL : https://stackoverflow.com/questions/12706161/in-typescript-how-do-i-declare-an-array-of-functions-that-accept-a-string-and-re

반응형