下午装了 typescript , 在坑里跌进爬出~~~
类型强制转换
在C#中,我们可以使用 (T)someVar 将someVar转换成类型T, 在typescript中,则使用 <T> someVar。
万能的 any
对于不知道类型的对象,例如由页面中的javascript传入的对象, 可以将其声明成 Any。
也可以将任意的对象强制转换为 any,从而绕过强类型检查。例如我们想为预定义的 window 对象增加一个属性,就可以采用:
//Cast to any, so we can add a property to an already defined class,
//otherwise the compiler stops on error: The property "x" does not exist on value of type 'Window'
(<any>window).x = someThing;
//otherwise the compiler stops on error: The property "x" does not exist on value of type 'Window'
(<any>window).x = someThing;
模拟名称空间
可以用 Module 模拟 C# 的 Namespace,例如:
module OuterMost {
export module Inner {
export function helloWorld() {
}
}
}
export module Inner {
export function helloWorld() {
}
}
}
注意最外层的 module 不要加 "export" , 否则生成的 javascript 会在文件末尾引用为定义的 "exports" 对象,从而在 javascript 运行过程中报 "Uncaught Reference Error: exports is not defined." 错误
模拟私有变量
Javascript 中,对象是没有私有成员的,在 typescript 中同样如此。但和在 javascript 中一样,可以通过在构造函数中定义成员的方式进行模拟。
module OuterMost {
//Cast to any, so we can add property to an already defined class,
//otherwise we will get the compiler error: The property "x" does not exist on value of type 'Window'
(<any>window).x = OuterMost; //define a short name of the module
export module Inner {
export function ThisIsStaticFunction() {
return "Can be called as OuterMost.Inner.ThisIsStaticFunction";
}
export class HelloWorld {
//Public method, note that function is also an object in javascript
public GetMessage: () => string;
constructor (message: string) {
//private member
var m_Message: string;
//Private method
var processMessage = function () {
return "Message processed for: " + m_Message;
};
//Creates the public method
this.GetMessage = function () {
return processMessage();
};
}
//Public method, cannot access the private members.
public GetMoreMessage(times: number): string[] {
//Cannot access the private members as they are realy local variables inside the constructor
//var x = m_Message;
var result: string[] = new Array();
for (var i = 0; i < times; i++) {
result[i] = this.GetMessage(); //public members can be accessed.
}
return result;
}
}
}
}
希望可以帮到调入同样坑里的~~~