TypeScript Type Innference (Type judgment) and typescript Type judgment

Source: Internet
Author: User

TypeScript Type Innference (Type judgment) and typescript Type judgment

TypeScript is a JavaScript superset developed by Microsoft. It is compatible with JavaScript and can load and run JavaScript code. Compared with JavaScript, TypeScript adds comments so that the compiler can understand the supported objects and functions. The compiler removes comments without increasing the overhead. It also adds a complete class structure, it is a traditional object-oriented language.

Why is there TypeScript?

JavaScript is just a scripting language, not designed for developing large Web applications. JavaScript does not provide classes and modules, and TypeScript extends JavaScript to implement these features. The main features of TypeScript include:

TypeScript is an open-source language released by Microsoft. It uses the Apache authorization protocol.

TypeScript is a JavaScript superset.

TypeScript adds optional types, classes, and modules.

TypeScript can be translated into readable, standard JavaScript

TypeScript supports the development of large-scale JavaScript applications

TypeScript is designed to develop large-scale applications and ensure the compatibility of compiled JavaScript code.

TypeScript extends the JavaScript syntax, so the existing JavaScript code can be directly run with TypeScript without changing

The TypeScript file extension is ts, while the TypeScript compiler will compile and translate the file into js files.

The TypeScript syntax is the same as that of JScript. NET.

TypeScript is easy to learn and understand

Syntax features

Class Classes

Interface Interfaces

Module Modules

Type annotation Type annotations

Compile-time type check Compile time type checking

Arrow function (similar to the Lambda expression of C)

Differences between JavaScript TypeScript

TypeScript is a JavaScript superset that extends the JavaScript syntax. Therefore, the existing JavaScript code can work with TypeScript without any modification. TypeScript provides a static type check during compilation through type annotations. TypeScript can process existing JavaScript code and only

Compile the TypeScript code.

In this section, we will introduce type inference in TypeScript. We will discuss where type inference needs to be used and how to deduce it.

Basic

In TypeScript, type inference is used to provide type information in a few places where type annotations are not explicitly specified.

Var x = 3;

The value of variable "x" is inferred as number. This inference occurs when variables or members are initialized, default parameter values are set, and function return types are determined.

Best Public type

When you need to deduce types from multiple expressions, the types of these expressions are used to deduce an "optimal public type ". For example:

Var x = [0, 1, null];

To deduce the type of "x" in an example, we need to consider the type of each array element. Here, we provide two types of Arrays: number and null. The best public type algorithm requires that all candidate types be taken into account and the types compatible with all candidate types should be selected. (The type here can be Array <number>)

Because the best common types are selected from the provided candidate types, in some cases, candidate types share a common type, but none of them are the parent types of all candidate types. For example:

Class Animal {name: string; constructor (theName: string) {this. name = theName ;}} class Snake extends Animal {constructor (name: string) {super (name) ;}} class Elephant extends Animal {constructor (name: string) {super (name) ;}} class Rhino extends Animal {constructor (name: string) {super (name) ;}} var zoo = [new Rhino (), new Elephant (), new Snake ()]; // The three member types are: Rhino, Elephant, and Snake. They are candidates of the best public type, animal is their super type (translated as parent type)

Ideally, we may want zoo to be inferred as the Animal [] type, but we cannot deduce it because no object in the array is of a strict Animal type. To solve this problem, when we cannot infer the parent types of all candidate types, We need to explicitly provide the types.

var zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()]; 

When there is no optimal public type, the inferred result is to generate an empty object ,{}. Because this type does not contain any members, access to any of its attributes will cause errors. This result still allows us to use objects in the ignore type method, but the object type cannot be implicitly determined while ensuring the type security.

Context type

In TypeScript, type inference also exists in "other aspects" in some cases ". This is called "context classification ". Context classification occurs when the type of an expression is implicitly specified in its context. For example:

Window. onmousedown = function (mouseEvent) {console. log (mouseEvent. buton); // <-an error thrown during compilation };

The above code will give a type error. the TypeScript type checker uses the Window. onmousedown function type to deduce the function expression type on the right. In this case, the type of the mouseEvent parameter can be inferred. If this expression is not in the position where context categorization is available, the mouseEvent parameter must be given an any type, so that no error will occur.

If the expression content that requires context categorization contains explicit type information, context categorization is ignored. Let's rewrite the example above:

Window. onmousedown = function (mouseEvent: any) {console. log (mouseEvent. buton); // <-no error reported now };

If the parameter explicitly specifies a type of function expression, context classification is ignored. After such processing, no error is reported, because no context category is applied.

Context categorization can be applied to many scenarios. Common scenarios include function call parameters, the expression on the right side of the value assignment, type determination, object members, array literal quantities, and return value statements. The context type is also a candidate type for the best public type. For example:

function createZoo(): Animal[] {return [new Rhino(), new Elephant(), new Snake()];} 

In this example, the optimal common types include Animal, Rhino, Elephant, and Snake. Here, Animal can be used as the best public type.

The form is a bit like finding the least common multiple in mathematics...

Articles you may be interested in:
  • Several different characteristics of TypeScript
  • JavaScript tank war game code re-compiled using TypeScript
  • Basic Types of TypeScript learning notes
  • Interface Details in TypeScript
  • C # programmer's understanding of TypeScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.