interface
- 在接口中定義方法
定義傳入?yún)?shù)和返回的類型
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
-
interface
的合并
與類型別名不同扫外,接口可以定義多次番官,會(huì)被自動(dòng)合并為單個(gè)接口。
interface Point { x: number; }
interface Point { y: number; }
const point: Point = { x: 1, y: 2 };
斷言
用<>
或者as
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;
在jsx里只能使用as語法
readonly
修飾符
表示屬性只讀蠕搜,無法被賦值并且無法賦給其他變量:
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
可以利用斷言重新賦值:
a = ro as number[];
類的readonly
屬性娇钱,只能在聲明時(shí)或者構(gòu)造函數(shù)里被初始化
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 錯(cuò)誤! name 是只讀的.
protected
修飾符
protected
成員在派生類中仍然可以訪問娇昙。
構(gòu)造函數(shù)也可以被標(biāo)記成 protected
旁钧。 這意味著這個(gè)類不能在包含它的類外被實(shí)例化骗露,但是能被繼承杯拐。比如
// Employee 能夠繼承 Person
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // 錯(cuò)誤: 'Person' 的構(gòu)造函數(shù)是被保護(hù)的.
枚舉
枚舉類型與數(shù)字類型兼容霞篡,并且數(shù)字類型與枚舉類型兼容。不同枚舉類型之間是不兼容的端逼。比如朗兵,
enum Status { Ready, Waiting };
enum Color { Red, Blue, Green };
let status = Status.Ready;
status = Color.Green; // Error