Home Web Front-end JS Tutorial TypeScript Type Innference (type judgment)_javascript skills

TypeScript Type Innference (type judgment)_javascript skills

May 16, 2016 pm 03:11 PM

TypeScript is a superset of JavaScript developed by Microsoft. TypeScript is compatible with JavaScript and can load JavaScript code and then run it. The improvements of TypeScript compared with JavaScript include: adding comments to let the compiler understand the supported objects and functions. The compiler will remove the comments without increasing overhead; adding a complete class structure to update it is a traditional orientation. object language.

Why is there TypeScript?

JavaScript is just a scripting language and is not designed to develop large-scale web applications. JavaScript does not provide the concepts of classes and modules, and TypeScript extends JavaScript to implement these features. TypeScript main features include:

TypeScript is an open source language launched by Microsoft and uses the Apache licensing agreement

TypeScript is a superset of JavaScript.

TypeScript adds optional types, classes and modules

TypeScript compiles to readable, standard JavaScript

TypeScript supports the development of large-scale JavaScript applications

TypeScript is designed for developing large-scale applications and guarantees compatibility of compiled JavaScript code

TypeScript extends the syntax of JavaScript, so existing JavaScript code can run directly with TypeScript without changes

TypeScript file extension is ts, and the TypeScript compiler will compile it into a js file

TypeScript syntax is the same as JScript .NET

TypeScript is easy to learn and understand

Grammatical features

Classes

Interfaces

Modules

Type annotations

Compile time type checking

Arrow function (similar to C#’s Lambda expression)

The difference between JavaScript and TypeScript

TypeScript is a superset of JavaScript that extends the syntax of JavaScript so that existing JavaScript code can work with TypeScript without any modification. TypeScript provides compile-time static type checking through type annotations. TypeScript can process existing JavaScript code and only use

TypeScript code is compiled.

In this section, we will introduce type inference in TypeScript. We'll discuss where type inference is needed and how to do it.

Basics

In TypeScript, type inference will be used to provide type information in several places where type annotations are not explicitly specified.

var x = 3;

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

Best Public Type

When type inference is required from multiple expressions, the types of these expressions will be used to infer a "best common type". For example:

var x = [0, 1, null];

To infer the type of "x" in the example, we need to consider the type of each array element. Here, we are given a choice of two array types: number and null. The best common type algorithm requires that all candidate types be considered and a type that is compatible with all candidate types be selected. (The type here can be Array)

Since the best common type is selected from the provided candidate types, there are cases where the candidate types share a common type, but no single type is the parent type of all candidate types. For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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()]; // 这里三个成员的类型分别为:Rhino、Elephant、Snake 他们是最佳公共类型的候选类型,Animal是他们的super type(译为父类型)

Copy after login

Ideally, we might want zoo to be inferred to be of type Animal[], but since no objects in the array are strictly of type Animal, we can't make that inference. To solve this problem, we need to provide the type explicitly when the parent type of all candidate types cannot be inferred.

1

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

Copy after login

When there is no best public type, the result of inference is to produce an empty object, {}. Because this type contains no members, accessing any of its properties will result in an error. This result still allows us to use the object in a type-ignoring manner, but the type of the object cannot be implicitly determined while ensuring type safety.

Context (Context) Type

In TypeScript, type inference also exists "otherwise" in some cases. This is called "contextual categorization". Contextual collation occurs when the type of an expression is implicitly specified in the context in which it occurs. For example:

1

2

3

window.onmousedown = function(mouseEvent) {

console.log(mouseEvent.buton); //<- 编译时抛出错误

};

Copy after login

上面的代码将会给出一个类型错误,TypeScript的类型检查器使用Window.onmousedown函数的类型来推断右边的函数表达式类型。当它这么做的时候,便能够推断出参数mouseEvent的类型。 如果这个表达式不在可进行上下文归类的位置,参数mouseEvent 需要给定一个any类型,这样就不会出现错误了。

如果需要上下文归类的表达式内容中包含明确的类型信息,则会忽略上下文归类。我们重写上面的例子:

1

2

3

window.onmousedown = function(mouseEvent: any) {

console.log(mouseEvent.buton); //<- 现在不会报错了

};

Copy after login

参数明确指定类型的函数表达式将会忽略上下文归类。经过这样的处理就不会报错了,因为没有应用到上下文归类。

上下文归类可应用于许多场景。常见的场景包括函数调用的参数、赋值的等号右边表达式、类型确定、对象成员和数组字面量、返回值语句。上下文类型也作为最佳公共类型的候选类型。例如:

1

2

3

function createZoo(): Animal[] {

return [new Rhino(), new Elephant(), new Snake()];

}

Copy after login

在这个例子中,最佳公共类型有四个候选类型:Animal,Rhino,Elephant,和Snake。其中,Animal可以作为最佳公共类型。

形式有点像数学中的求最小公倍数...

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

From Websites to Apps: The Diverse Applications of JavaScript From Websites to Apps: The Diverse Applications of JavaScript Apr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles