2019年11月19日 星期二

y分學typescript

為什麽學

它能讓專案更加可靠,像一般用Javascript寫程式不宣告型別很方便,少打幾個字。可是遇到要用這個變數時,會疑惑著個變數究竟是什麽型別,型別不知道誤用函數,就會造成很多不必要的錯誤。

用typescript強型別的語言,強型別就是使用變數前必須宣告型別的意思,用這個語言能減少變數型別的問題。

步驟

  1. 下載安裝Node.js
  2. 安裝typescript指令 npm install -g typescript
  3. 建立檔案first-typescript.ts。
  4. 寫程式。
  5. 編譯.ts 檔案為 .js 指令 tsc first-typescript.ts

first-typescript.ts程式碼

//1.Install typescript
// npm install -g typescript
//2.Create a file first-typescript.ts
//3.Coding
//4.Compile .ts file to .js file.
// tsc first-typescript.ts
let a = 5;
let b = 5;
let c = a + b;
console.log(c);
let myVariable: any = 'This is a string'
console.log('any type:'+myVariable);
let num: number = 5;
let name1: string = 'Alex';
let isPresent: boolean = true;
let num1: void;
let name_a: undefined;
let isPresent1:null;
console.log('built-in types:'+name1);
let numbers: Array<number> = [0, 1, 2, 3, 4];
let moreNumbers: ReadonlyArray<number> = numbers;
//moreNumbers[5] = 5; // Error, elements are read-only
enum Color { Red, Green, Blue };
let color: Color = Color.Green;
console.log('user-defined types');
class Car {
// fields
model: String;
doors: Number;
isElectric: Boolean;
constructor(model: String, doors: Number, isElectric: Boolean) {
this.model = model;
this.doors = doors;
this.isElectric = isElectric;
}
displayMake(): void {
console.log(`This car is ${this.model}`);
}
}
const Prius = new Car('Prius', 4, true);
Prius.displayMake(); // This car is Prius
console.log('class test');
interface ICar {
model: String,
make: String,
display(): void
}
const UberCar: ICar = {
model: 'Prius',
make: 'Toyota',
display():void { console.log('hi'); }
}
console.log('use interface to define the structure of variables.');
// Generics
// Classes
class Tuple<T1, T2> {
constructor(public item1: T1, public item2: T2) {
}
}
// Interfaces
interface Pair<T> {
item1: T;
item2: T;
}
// And functions
let pairToTuple = function <T>(p: Pair<T>) {
return new Tuple(p.item1, p.item2);
};
let tuple = pairToTuple({ item1: "hello", item2: "world" });
console.log('tuple example');

參考


如果你覺得這篇文章很有用,可以請我喝杯咖啡,讓我提供更多優質文章給您。感謝所有支持的朋友。

Vere Perrot 資訊人.科技人.行銷人,現為軟體分析師。定位自己為網路觀察家,永遠保持好奇心與熱情,學習跨領域新事物,希望最終能成為一個全方位的人。 Mail: vereperrot@gmail.com

沒有留言: