문서의 이전 판입니다!
There are many types in typescript, but since we love callback function in javascript, how do we declare them in typescript? Let's take a look from the bottom to the top. And with along some practice thinking.
타입스크립트에는 많은 타입들이 있지만, 우리는 자바스크립트의 콜백함수를 선호하는 이유로 해서, 타입스크립트에서는 그것을 어떻게 선언할까? 밑의 예제를 보고 위로 보면서, 예행적 사고를 가지기 바랍니다.
OK, this is the most ugly way to achieve it, you can simply declare a variable as any type, then later, you can assign a function to it. It's not recommend.
좋아, 이것은 가장 못난 접근 방법이다, 당신은 any타입의 변수를 단순히 선언하고 그것에 함수를 할당한다. 이것을 추천하지 않는다.
<Code:typescript> let a: any;
a = function (): void {
console.log('It works');
} </Code>
Sometimes, when you design the interfaces, you have no idea what the actual signature will be, but instead declaring a 'any' type, you can use a keyword 'Function', so you can take advantage of the type checking later.
때로는 인터페이스를 디자인 할 때 실제 서명이 무엇인지 모르지만 'any'유형을 선언하는 대신 키워드 'Function'를 사용하여 나중에 유형 확인을 활용할 수 있습니다.
<Code:typescript> let a: Function;
a = function(): void {
console.log('It works');
}
</Code>
OK. So now when you want assign a value other than function to this variable 'a', the compiler will throw an error :
Type 'xxxxx' is not assignable to type 'Function'
Now, as your projets goes on, you have whole idea of what's going on there. So you can go back and modify your declaration to a more precise version using the fancy arrow function syntax, feel free to use it, it maked as 'standard' in ECMA2015.
<Code:typescript> let a: (para: string) ⇒ string; a = function(pass: string): string {
return pass; }
</Code>
The syntax here is very simple, it is just like the lambda function in Java or C#, the 'string' after the arrow is the type of the return value. The para: string defines the type of the parameter. It takes a string and return a string.
We can use type to declare a function type:
<Code:typescript> type read = (name: string) ⇒ void; const test: read = (value: string) ⇒ {
console.log(value);
} </Code>
We are Typescript, we'd love to use the beloved interface for everything, well, you can, for just a function.
<Code:typescript>
interface read {
(name: string): string;
}
const test: read = (value: string) ⇒ value; </Code>
In pratice, I often use Solution 4 - Type. Maybe juse because it looks simpler than interface version.