Typescript 为逻辑参数声明自定义类型

Typescript 为逻辑参数声明自定义类型,typescript,Typescript,前言:我目前正在为现有的js库创建类型定义 我目前正在使用的代码使用了大量类似以下的方法: class SomeClass { someMethod(product, label) { const productName = product.ownName || product.title || product; const labelId = labelIdNumber || label // do some stuff here } } 由于可以直接传递某个对

前言:我目前正在为现有的js库创建类型定义

我目前正在使用的代码使用了大量类似以下的方法:

class SomeClass {
  someMethod(product, label) {
    const productName = product.ownName || product.title || product;
    const labelId = labelIdNumber || label
  // do some stuff here
  }
}

由于可以直接传递某个对象一个值(例如字符串),因此这对于库来说非常有用

然而,我很难理解在这种情况下如何正确使用泛型。我正在尝试类似的东西:

interface SomeClass {
  someMethod<T>(product: T, label: T): void
}

所以我的问题是如何创建一个
类型
,它将声明参数是
对象
字符串

基本上我需要一个类型,将这样做

interface SomeClass {
  someMethod(product: Object | string, label: : Object | string): void
}

为什么??因为这种使用
Object | | string
的方法在整个库中都被使用,我希望有一些独特的类型用于此,而不是将
Object | string
写入100次

您可以在
d.ts
文件中执行
导出类型ObjectOrString=Object | string
。然后是
product:ObjectOrString
interface SomeClass {
  someMethod(product: Object | string, label: : Object | string): void
}