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:

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.

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:

window.onmousedown = function(mouseEvent) { 
console.log(mouseEvent.buton); //<- 编译时抛出错误 
}; 
Copy after login

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

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

window.onmousedown = function(mouseEvent: any) { 
console.log(mouseEvent.buton); //<- 现在不会报错了 
}; 
Copy after login

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

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles