在打字稿中精炼泛型

Refining generic type in typescript

在 google 闭包编译器中,您可以通过执行 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;
}

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

These typeof type guards are recognized in two different forms: typeof v === "typename" and typeof v !== "typename", where "typename" must be "number", "string", "boolean", or "symbol". While TypeScript won’t stop you from comparing to other strings, the language won’t recognize those expressions as type guards.

第二个将是一个有效的使用,一旦他们修复 this bug (there is already a PR)。