【问题标题】:Generics in TypeScriptTypeScript 中的泛型
【发布时间】:2012-10-04 21:54:39
【问题描述】:

除了使用类型化数组之外,还有没有办法在 TypeScript 中用另一种类型参数化一个类型?

KnockoutJs 真的很有必要。

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

    目前尚不支持泛型,但正在考虑中。以下是规范的内容:

    注意:TypeScript 目前不支持泛型,但我们希望将它们包含在最终语言中。 由于 TypeScript 的静态类型系统没有运行时表现,泛型将基于“类型擦除” 并且纯粹用作在接口、类和 函数签名。

    来自第 3 节末尾的 TypeScript 语言规范。

    【讨论】:

    【解决方案2】:

    泛型终于来了:http://blogs.msdn.com/b/typescript/archive/2013/06/18/announcing-typescript-0-9.aspx

    目前它处于测试阶段,因此请谨慎使用。

    【讨论】:

      【解决方案3】:

      我正在使用一个相当肮脏的解决方法。可以将类分配给任何类型的变量。此代码有效:

      class A{}
      var test:any=A;
      var a=new test();
      

      因此,您可以通过添加另一个 any 类型的参数来参数化您的方法

      function(param:any){
          var test=new param();
          test.someFunction();
      }
      

      当然,这是非常糟糕的风格,可能不推荐。但对我来说,它将涵盖泛型包含在语言中的时间。

      【讨论】:

        【解决方案4】:

        对于像我这样遇到这个问题的人来说,既然我们在 TypeScript 中有泛型,这里有更多信息,包括 Typescript 网站上泛型官方文档的链接,因为这很好地解释了它,希望能一直保持下去-迄今为止所做的更改,并显示示例用法:

        https://www.typescriptlang.org/docs/handbook/generics.html

        泛型允许创建可以在多种类型而不是单一类型上工作的组件。

        如官方文档中所示,标识函数是泛型在工作中最基本的说明。身份函数是一个函数,它会返回传入的任何内容。

        这是我们在泛型之前的选择:

        // without Generics option 1 - explicitly define and get tied to a single type.  
        function identity(arg: number): number {
            return arg;
        }
        
        // without Generics option 2 - use the 'any' type 
        // but lose type information on the incoming arg by the time we return it.
        function identity(arg: any): any {
            return arg;
        }
        

        下面是它如何与泛型一起使用:

        // with Generics - use a type variable T that works on types rather than values. 
        // Captures the type of incoming arg so we can use it again in the return type
        function identity<T>(arg: T): T {
            return arg;
        }
        
        // can call it with explicit setting of T to be a given type ('string' here)
        let output = identity<string>("myString");  // type of output will be 'string'
        
        // However can also call it without this explicit typing and the compiler will 
        // infer the type. Note this won't always work for more complex Generics usage
        let output = identity("myString");  // type of output will be 'string'
        

        【讨论】:

          猜你喜欢
          • 2020-07-23
          • 2019-05-30
          • 2017-11-05
          • 2020-04-12
          • 2019-10-06
          • 2019-10-07
          • 2020-01-05
          • 2019-07-09
          • 1970-01-01
          相关资源
          最近更新 更多