打字稿:强制默认通用类型为“任意"而不是"{}"
问题描述:
我有一个函数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