1
在google閉包編譯器中,您可以通過執行typeof或instanceof來優化泛型。 例如,下面我帶一個通用的,把它當作一個對象:在typescript中精煉泛型類型
/**
* @param {T} obj
* @return {T}
* @template T
*/
function cloneIfObject(obj) {
if (typeof obj === 'object') {
return objectClone(obj);
}
return obj;
}
/**
* Stub function that only accepts object type
*
* @param {!Object} obj
* @return {!Object}
*/
function objectClone(obj) {
return obj; //Pretend to clone
}
我試着在打字稿實現這一點,但我不能把它當作一個對象。
function cloneIfObject<T>(obj: T) {
if (typeof obj === 'object') {
return { ...obj }; //Error: Spread types may only be created from object types.
}
if (obj instanceof Object) {
return { ...obj }; //Error: Spread types may only be created from object types.
}
return obj;
}
您是否嘗試添加演員?像'{...
@ A.Akram演員仍然失敗'Type'{}'不能分配給'T'類型。' 你說得對,'Object.assign'和spread是一樣的。我認爲'Object.assign({},
不使用泛型類型參數的泛型函數,很棒 – Dummy