【问题标题】:Typescript: Force Default Generic Type to be `any` instead of `{}`打字稿:强制默认通用类型为“any”而不是“{}”
【发布时间】:2016-01-22 03:41:16
【问题描述】:

我有一个函数a,如果没有提供泛型类型,它应该返回any,否则返回T

var a = function<T>() : T  {
    return null;
}
var b = a<number>();    //number
var c = a();    //c is {}. Not what I want... I want c to be any.
var d; //any
var e = a<typeof d>();  //any

有可能吗? (没有明显改变函数调用。没有a&lt;any&gt;()的AKA。)

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

    有可能吗? (显然没有改变函数调用。AKA 没有 a()。)

    是的。

    我相信你会这样做

    var a = function<T = any>() : T  {
        return null;
    }
    

    TS 2.3 中引入了通用默认值。

    泛型类型参数的默认类型具有以下语法:

    TypeParameter :
      BindingIdentifier Constraint? DefaultType?
    
    DefaultType :
      `=` Type
    

    例如:

    class Generic<T = string> {
      private readonly list: T[] = []
    
      add(t: T) {
        this.list.push(t)
      }
    
      log() {
        console.log(this.list)
      }
    
    }
    
    const generic = new Generic()
    generic.add('hello world') // Works
    generic.add(4) // Error: Argument of type '4' is not assignable to parameter of type 'string'
    generic.add({t: 33}) // Error: Argument of type '{ t: number; }' is not assignable to parameter of type 'string'
    generic.log()
    
    const genericAny = new Generic<any>()
    // All of the following compile successfully
    genericAny.add('hello world')
    genericAny.add(4)
    genericAny.add({t: 33})
    genericAny.log()
    

    https://github.com/Microsoft/TypeScript/wiki/Roadmap#23-april-2017https://github.com/Microsoft/TypeScript/pull/13487

    【讨论】:

      【解决方案2】:

      有可能吗? (显然不改变函数调用。AKA 没有 a()。)

      没有。

      PS

      请注意,没有在任何函数参数中主动使用的泛型类型几乎总是一个编程错误。这是因为以下两个是等价的:

      foo&lt;any&gt;()&lt;someEquvalentAssertion&gt;foo() 完全由调用者支配。

      PS PS

      有一个官方问题要求使用此功能:https://github.com/Microsoft/TypeScript/issues/2175

      【讨论】:

      【解决方案3】:

      对于稍微不同的应用程序更进一步,但您也可以将类型参数默认为另一个类型参数。

      举个例子:

      class Foo<T1 = any, T2 = T1> {
          prop1: T1;
          prop2: T2;
      }
      

      等等:

      const foo1 = new Foo();
      typeof foo1.prop1 // any
      typeof foo1.prop1 // any
      
      const foo2 = new Foo<string>();
      typeof foo2.prop1 // string
      typeof foo2.prop2 // string
      
      const foo3 = new Foo<string, number>();
      typeof foo3.prop1 // string
      typeof foo3.prop1 // number
      

      【讨论】:

        猜你喜欢
        • 2019-12-06
        • 2021-06-16
        • 1970-01-01
        • 2017-05-16
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多