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