打字稿:强制默认通用类型为“任意"而不是"{}" [英] Typescript: Force Default Generic Type to be `any` instead of `{}`

查看:60
本文介绍了打字稿:强制默认通用类型为“任意"而不是"{}"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数a,如果未提供通用类型,则应返回any,否则返回T.

I have a function a that should returns any if no generic type is provided, T otherwise.

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<any>()的AKA.)

Is it possible? (Without changing the function calls obviously. AKA without a<any>().)

推荐答案

有可能吗? (显然,无需更改函数调用.AKA不包含a().)

Is it possible? (Without changing the function calls obviously. AKA without a().)

是的

我相信您会这么做

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

通用默认设置在TS 2.3中引入.

Generic defaults were introduced in TS 2.3.

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

Default types for generic type parameters have the following syntax:

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-2017 https://github.com/Microsoft/TypeScript/pull/13487

这篇关于打字稿:强制默认通用类型为“任意"而不是"{}"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆