2016-01-22 313 views
3

我有一个函数a,如果没有提供泛型类型,应该返回any,否则返回TTypescript:强制默认泛型类型为'any`而不是`{}`

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 

这可能吗? (不用就可以改变函数调用。)

回答

6

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

是的。

我相信你的情况,你会怎么做

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

4

可能吗? (在不改变功能显然要。AKA没有()。)

PS

注意,具有不积极任何函数的参数使用的通用型几乎是总是出现编程错误。这是因为以下两个是等价的:

foo<any>()<someEquvalentAssertion>foo()并且完全由调用者支配。

PS PS

有请求该功能正式的问题:https://github.com/Microsoft/TypeScript/issues/2175

+1

这里的目标是使通用型可选。我目前正在将JS转换为TS文件,如果这能起作用,那将会有很大帮助。 – RainingChain

+0

请参阅https://github.com/Microsoft/TypeScript/issues/2175。目前不可能 – basarat