如何使用或输入 TypeScript 泛型

Mun*_*abu -1 typescript

我试图为其中任何一个提供通用方法的打字匹配。在下面的示例中,我有一个预定义的方法识别,它接受通用类型。现在我想定义 OR 类型来识别,它应该接受人或位置。

身份方法来自我无法修改的第三方库。当我尝试下面的场景时,它返回了一个错误

Argument of type '{ city: string; country: string; }' is not assignable to parameter of type 'Person | Location'.
  Type '{ city: string; country: string; }' is missing the following properties from type 'Location': ancestorOrigins, hash, host, hostname, and 9 more.
Run Code Online (Sandbox Code Playgroud)
function identity<Type>(arg: Type): Type {
  return arg;
}

interface Person {
  name: string;
  age: number;
}

interface Location {
  city: string;
  country: string;
}

identity<Person | Location>({city: 'SA', country: 'USA'})
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 5

我相信这里发生的事情是Location与全球Location类型的碰撞/合并lib.dom.d.ts

如果你给它另一个名字,例如:MyLocation它应该可以正常工作。

lib.dom.d.ts另一种选择是,如果您不在 Web 浏览器环境中(例如:您正在编写 NodeJS 应用程序),则禁用这些类型 - 我建议使用https://github.com/tsconfig/bases中的基本配置NodeJS 项目如果是的话。