2016-01-22 85 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