一般咱們使用第三方庫,能夠javascript
<script>
標籤引入;import
引入;看慣了以前的引入方式,那 Typescript 咋用的呢?看下面這個例子前端
// declareVar.ts
declare var $$: (selector: string) => any;
$$('#root');
複製代碼
編譯後java
// declareVar.js
$$('#root');
複製代碼
可見 declare var
只是定義一個全局變量的類型(不是定義一個全局變量),僅在編譯時用於檢查,不會存在與編譯的結果中。jquery
存放聲明語句的文件,叫聲明文件,一般格式爲 xxx.d.ts
。仍是拿 jQuery
舉例git
1.聲明文件 jQuery.d.ts
(抽離出生命語句)github
// jQuery.d.ts
declare const jQuery2: (selector: string) => any;
複製代碼
2.typescript 文件typescript
// declareVar2.ts
jQuery2('#root');
複製代碼
3.編譯後npm
jQuery2('#root');
複製代碼
jQuery.d.ts
文件與 declareVar2.ts
同處一個目錄;declare const jQuery2
這是全局變量聲明模式;*.ts
文件(含 *.d.ts
),因此 declareVar2.ts
能夠得到 jQuery2
類型定義;既然像 jQuery.d.ts
這類不少人都須要的聲明文件,社區確定會作些什麼,好比 DefinitelyTyped jQuery。既然社區都寫好了,那就不造輪子直接下載咯。關於下載,可將其下載到本地 @types
目錄下,便於識別與統一管理這類聲明文件。bash
npm install @types/jquery
複製代碼
// declareVar3.ts
const jQuery = require('jquery');
const $ = require('jquery');
jQuery('#root')
$('#root')
複製代碼
對於社區爲哪些第三方庫寫了聲明文件,可在這裏查詢 microsoft.github.io/TypeSearch/前端工程師
實際場景中,對於定義了兩個相同名字的函數、接口或類,它們會合併成一個類型。
看個迴文的例子
// functionMerge.ts
function palindrome(x: string): string;
function palindrome(x: number): number;
function palindrome(x: string | number): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}
console.log(palindrome('pr18')); // 81rp
複製代碼
就是將各接口的屬性合併起來。
// interfaceMerge.ts
interface Station {
name: string;
time: string;
showName(): string;
}
interface Station {
name: string;
time: number;
showTime(): string;
}
let station: Station = {
name: '前端工程師',
time: 18,
showName: function() {
return `我是一名${this.name}`;
},
showTime: () => {
return `工做已有${station.time}年了`;
}
}
console.log(station.showName()); // 我是一名前端工程師
console.log(station.showTime()); // 工做已有8年了
// 0.1.3/interfaceMerge.ts:8:5 - error TS2717: Subsequent property declarations must have the same type. Property 'time' must be of type 'string', but here has type 'number'.
// 8 time: number;
// 0.1.3/interfaceMerge.ts:3:5
// 3 time: string;
// 'time' was also declared here.
// 0.1.3/interfaceMerge.ts:14:5 - error TS2322: Type 'number' is not assignable to type 'string'.
// 14 time: 18,
// 0.1.3/interfaceMerge.ts:3:5
// 3 time: string;
// The expected type comes from property 'time' which is declared here on type 'Station'
複製代碼
上面報錯緣由是重複定義 age
時改變了其類型。可見,接口的屬性在多個接口中可重複定義,但其類型必須惟一。
和接口的合併同樣,就不寫了。
// namespaceMerge.ts
namespace NamespaceMerge {
export function one(){}
}
namespace NamespaceMerge {
export function two(){}
}
NamespaceMerge.one();
複製代碼
這裏必需要導出,由於不導出就算是合併了,外面也是訪問不到,看下圖