any表示任意類型
void則可以看作與any相反掉伏,意思是沒有類型宜鸯,通常一個(gè)函數(shù)如果沒有返回值,那么就可以把他的返回類型設(shè)置為void罢坝。
protected componentWillUnmount():void {
}
在TypeScript里,每個(gè)成員默認(rèn)為public的搅窿。
那么他的實(shí)例和繼承他的類的實(shí)例是可以調(diào)用這些方法或變量的嘁酿。
當(dāng)成員被標(biāo)記成private時(shí),它就不能在聲明它的類的外部訪問男应。比如:
class Animal {
private name: string;
constructor(theName: string) {
this.name = theName;
}
}
new Animal("Cat").name; // Error: 'name' is private;
protected
修飾符與private
修飾符的行為很相似痹仙,但有一點(diǎn)不同,protected
成員在派生類中仍然可以訪問殉了,就是說开仰,他的實(shí)例不可以訪問這些變量或方法,但是他的子類的實(shí)例可以薪铜。
有時(shí)候我們希望用戶可以輸入任何類型的值的同時(shí)众弓,又希望返回的類型能夠確定,那么就用到泛型了隔箍。
function identity<T>(arg: T): T {
return arg;
}
泛型類
泛型類看上去與泛型接口差不多谓娃。 泛型類使用(<>
)括起泛型類型,跟在類名后面蜒滩。
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
GenericNumber類的使用是十分直觀的滨达,并且你可能已經(jīng)注意到了,沒有什么去限制它只能使用number類型俯艰。 也可以使用字符串或其它更復(fù)雜的類型捡遍。
let stringNumeric = new GenericNumber<string>();
stringNumeric.zeroValue = "";
stringNumeric.add = function(x, y) { return x + y; };
alert(stringNumeric.add(stringNumeric.zeroValue, "test"));