[TypeScript] type inference

The TypeScript type system enables programmers to express limits on the capabilities of JavaScript objects, and to use tools that enforce these limits. To minimize the number of annotations needed for tools to become useful, the TypeScript type system makes extensive use of type inference. For example, from the following statement, TypeScript will infer that the variable ‘i’ has the type number.

var i = 0;

TypeScript will infer from the following function definition that the function f has return type string.

function f() {
    return "hello";
}

To benefit from this inference, a programmer can use the TypeScript language service. For example, a code editor can incorporate the TypeScript language service and use the service to find the members of a string object as in the following screen shot.

Image showing string members in editor

In this example, the programmer benefits from type inference without providing type annotations. Some beneficial tools, however, do require the programmer to provide type annotations. In TypeScript, we can express a parameter requirement as in the following code fragment.

function f(s: string) {
    return s;
}

f({});       // Error
f("hello");  // Ok

This optional type annotation on the parameter ‘s’ lets the TypeScript type checker know that the programmer expects parameter ‘s’ to be of type ‘string’. Within the body of function ‘f’, tools can assume ‘s’ is of type ‘string’ and provide operator type checking and member completion consistent with this assumption. Tools can also signal an error on the first call to ‘f’, because ‘f’ expects a string, not an object, as its parameter. For the function ‘f’, the TypeScript compiler will emit the following JavaScript code:

function f(s) {
    return s;
}

In the JavaScript output, all type annotations have been erased. In general, TypeScript erases all type information before emitting JavaScript.

posted @ 2015-08-17 19:30  Zhentiw  阅读(286)  评论(0)    收藏  举报