Smartkid's binary life

博客园 首页 联系 订阅 管理
  10 随笔 :: 1 文章 :: 24 评论 :: 25127 阅读

 下午装了 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;    

 

 

 

模拟名称空间

可以用 Module 模拟 C# 的 Namespace,例如:

module OuterMost {
  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;
            }
        }
    }
}

复制代码


希望可以帮到调入同样坑里的~~~ 

posted on   Smartkid  阅读(1707)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示