在打字稿

时间:2017-05-14 16:07:08

标签: javascript typescript google-closure-compiler

在谷歌闭包编译器中,您可以通过执行typeof或instanceof来优化通用。 例如,在这里我采用泛型并将其视为对象:

/**
 * @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;
}

1 个答案:

答案 0 :(得分:2)

您不能将typeof用于您要执行的操作:

  

这些类型的防护装置以两种不同的形式识别:typeof   v ===“typename”和typeof v!==“typename”,其中“typename”必须是   “number”,“string”,“boolean”或“symbol”。虽然TypeScript不会   阻止你与其他字符串比较,语言将无法识别   那些表达式作为类型保护。

第二个是有效用途,只要他们修复this bug(已经有PR)。

相关问题