1. 程式人生 > 其它 >加深TS開發使用,類實現介面

加深TS開發使用,類實現介面

1.實現類,必須實現Car資料介面

/** 定義資料型別 */
interface Car {
    wheel: number;
    color: string;
    say: () => void;
}
type CarProp = {
    wheel: 4 | 6;
    color: string;
}

// 實現一個類,這個類必須實現Car介面
// Class 'MyCar' incorrectly implements interface 'Car'.
//   Type 'MyCar' is missing the following properties from type 'Car': wheel, color, say
class MyCar implements Car { wheel: number color: string // 可以指定資料型別 constructor(obj: CarProp) { this.wheel = obj.wheel this.color = obj.color } say() { console.log(`我們的汽車有${this.wheel}個輪胎, 是${this.color}`) } // 在方法的圓括號後使用: 來指定方法返回的資料型別 drive(name: string): string {
return `${name} 有駕駛許可權` // return 1 } } // Argument of type '8' is not assignable to parameter of type '4 | 6'. // const myCar = new MyCar(8, '紅色') error // const myCar = new MyCar(6, '紅色') const myCar = new MyCar({wheel: 6, color: '紅色'}) myCar.say() // console.log(myCar.drive(12)) console.log(myCar.drive('張三'))
/********************************************************** 泛型 */ function test<T>(obj: T) { if (!!obj) { return obj } else { return {id: 'test'} } } console.log(test({id: '有傳遞的值'})) console.log(test(null)) //tsc 編譯

編譯後程式設計js檔案

 

 2.名稱空間寫法

 

 名稱空間裡是私有寫法,外部用不了,只有模組匯出export才可以供給外部使用

3.修飾符決定類方法裡的 變數私有是否供給外部決定

 

 如果在裡面有匯入其他檔案,則會將其他關聯的檔案也一併進行了轉換js檔案,這是搖樹機制