首頁 web前端 js教程 TypeScript Type Innference(類型判斷)_javascript技巧

TypeScript Type Innference(類型判斷)_javascript技巧

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(译为父类型) 
登入後複製

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()]; 
登入後複製

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); //<- 编译时抛出错误 
}; 
登入後複製

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

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

window.onmousedown = function(mouseEvent: any) { 
console.log(mouseEvent.buton); //<- 现在不会报错了 
}; 
登入後複製

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

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

function createZoo(): Animal[] {
return [new Rhino(), new Elephant(), new Snake()];
} 
登入後複製

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

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1422
52
Laravel 教程
1316
25
PHP教程
1267
29
C# 教程
1239
24
神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

JavaScript的演變:當前的趨勢和未來前景 JavaScript的演變:當前的趨勢和未來前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

JavaScript:探索網絡語言的多功能性 JavaScript:探索網絡語言的多功能性 Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

如何使用Next.js(前端集成)構建多租戶SaaS應用程序 如何使用Next.js(前端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

使用Next.js(後端集成)構建多租戶SaaS應用程序 使用Next.js(後端集成)構建多租戶SaaS應用程序 Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

See all articles