打字稿:强制默认通用类型为"任何"而不是"{}"

Rai*_*ain 4 generics typescript

如果没有提供泛型类型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
Run Code Online (Sandbox Code Playgroud)

可能吗?(显然没有改变函数调用.没有AKA a<any>().)

lau*_*gan 14

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

是.

我相信你会这样做

var a = function<T = any>() : T  {
    return null;
}
Run Code Online (Sandbox Code Playgroud)

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

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

TypeParameter :
  BindingIdentifier Constraint? DefaultType?

DefaultType :
  `=` Type
Run Code Online (Sandbox Code Playgroud)

例如:

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()
Run Code Online (Sandbox Code Playgroud)

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