IT story

TypeScript에서 함수의 반환 유형을 선언하는 방법

hot-time 2020. 8. 30. 19:47
반응형

TypeScript에서 함수의 반환 유형을 선언하는 방법


TypeScript 언어 사양 인 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md여기에서 확인 했지만 함수의 반환 유형을 선언하는 방법에 대한 한 가지를 볼 수 없었습니다. 나는 아래 코드에서 내가 기대했던 것을 보여 주었다.greet(name:string) :string {}

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string{
        return "Hello, " + this.greeting;
    }
}  

나는 우리가 무언가를 사용할 수 있다는 것을 (name:string) => any알지만 그들은 주로 콜백 함수를 전달할 때 사용됩니다.

function vote(candidate: string, callback: (result: string) => any) {
// ...
}

당신이 맞습니다-여기 완전히 작동하는 예제가 있습니다- var result반환 유형이 greet()함수에 지정되어 있기 때문에 암시 적으로 문자열 임을 알 수 있습니다 . 유형을로 변경하면 number경고가 표시됩니다.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string {
        return "Hello, " + this.greeting;
    }
} 

var greeter = new Greeter("Hi");
var result = greeter.greet();

다음은 숫자의 예입니다.이 작업을 시도하면 플레이 그라운드 편집기에 빨간색 물결 선이 표시됩니다.

greet() : number {
    return "Hello, " + this.greeting;
}

3.5.3.5 및 3.5.5 섹션 언어 사양 에서 함수 유형에 대한 자세한 내용을 읽을 수 있습니다 .

TypeScript 컴파일러는 가능한 경우 유형을 추론하므로 명시 적 유형을 지정할 필요가 없습니다. 따라서 greeter 예제의 경우 greet ()는 문자열 리터럴을 반환하여 컴파일러에게 함수의 유형이 문자열이며 유형을 지정할 필요가 없음을 알려줍니다. 예를 들어이 샘플에는 문자열을 반환하는 greet 메서드와 숫자 리터럴에 할당 된 변수가있는 greeter 클래스가 있습니다. 컴파일러는 두 유형을 모두 추론하고 숫자에 문자열을 할당하려고하면 오류가 발생합니다.

class Greeter {
    greet() {
        return "Hello, ";  // type infered to be string
    }
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

마찬가지로,이 샘플은 정보가 주어지면 컴파일러가 유형을 결정할 방법이 없으므로 오류가 발생하며 여기에서 명시적인 반환 유형이 있어야합니다.

function foo(){
    if (true)
        return "string"; 
    else 
        return 0;
}

This, however, will work:

function foo() : any{
    if (true)
        return "string"; 
    else 
        return 0;
}

functionName() : ReturnType { ... }

Return types using arrow notation is the same as previous answers:

const sum = (a: number, b: number) : number => a + b;

참고URL : https://stackoverflow.com/questions/12736269/how-to-declare-return-types-for-functions-in-typescript

반응형