我有一个函数 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<any>()
。)
最佳答案
Is it possible? (Without changing the function calls obviously. AKA without 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-2017和 https://github.com/Microsoft/TypeScript/pull/13487
关于generics - typescript :强制默认通用类型为 `any` 而不是 `{}`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938617/