深入理解TypeScript——第一章:上手篇
- 2020 年 9 月 25 日
- 筆記
- typescript
怎麼定義TypeScript呢? TypeScript是一個工具 是一個編譯器
1、編譯程式碼
TypeScript,通過它的能力,默認使用tsc命令,可以根據.ts為後綴名的文件生成一個新的js文件
2、類型註解
TypeScript里的類型註解是一種輕量級的為函數或變數添加約束的方式。TypeScript提供了靜態的程式碼分析,它可以分析程式碼結構和提供的類型註解。
function doSth(who: string): string {
return "I want to say hello to " + who;
}
let who = 'her';
const doWhat = doSth(who);
console.log('doWhat:', doWhat)
// doWhat: I want say hello to her
這裡插個題外話,如果部分語法產生error的話,要考慮tsconfig.json這樣的配置文件(比如lib部分)是否支援了你需要的Javascript規範,如果不支援的話,建議使用polyfill
3、介面
允許我們在實現介面時候只要保證包含了介面要求的結構就可以
interface Girl {
hair: string;
face: string;
}
function describe(girl: Girl): string {
let words = 'she has '
let decs = Object.entries(girl)
let len = decs.length
for (let i = 0; i < len; i++) {
const [where, like] = decs[i];
words+=(like + ' ' + where)
words+=(i === len - 1 ? '' : ' and ')
}
return words
}
const sentence = describe({
hair: 'long',
face: 'beautiful'
})
console.log('sentence:', sentence);
// sentence: she has long hair and beautiful face
4、類
支援基於類的面向對象編程
在構造函數的參數上使用public等同於創建了同名的成員變數
class She {
praise: string;
constructor(public hair: string, public face: string) {
// this.praise = hair + ' hair' + " and " + face + ' face';
}
}
interface Girl {
hair: string;
face: string;
}
function describe(girl: Girl): string {
let words = 'she has '
let decs = Object.entries(girl)
let len = decs.length
for (let i = 0; i < len; i++) {
const [where, like] = decs[i];
words+=(like + ' ' + where)
words+=(i === len - 1 ? '' : ' and ')
}
return words
}
const she = new She('long', 'beautiful')
const sentence = describe(she)
console.log('sentence', sentence);
上面這段程式碼通過ts編譯,成為了下面這段程式碼
var She = /** @class */ (function () {
function She(hair, face) {
this.hair = hair;
this.face = face;
// this.praise = hair + ' hair' + " and " + face + ' face';
}
return She;
}());
function describe(girl) {
var words = 'she has ';
var decs = Object.entries(girl);
var len = decs.length;
for (var i = 0; i < len; i++) {
var _a = decs[i], where = _a[0], like = _a[1];
words += (like + ' ' + where);
words += (i === len - 1 ? '' : ' and ');
}
return words;
}
var she = new She('long', 'beautiful');
var sentence = describe(she);
console.log('sentence', sentence);
看起來,只是多了一些特殊的注釋,以及修改了一些局部變數名,所以ts主要的功能其實是為了規範書寫,校驗傳入參數是否正確,從而實現更高品質的程式碼!