打字稿 - 如何在不使用 Exclude<> 的情况下从泛型类型中排除类型?



我有一个函数,通过字符串化将不同的值存储到本地存储中,我想限制该函数能够使用 Moment 对象。语法是这样的:

public static set<TValue>(
key: LocalStorageKeyEnum,
value: TValue,
...keySuffixes: string[]
) {
localStorage.setItem(
LocalStorage.buildKey(key, keySuffixes),
JSON.stringify(value)
)
}

问题是如果第二个参数是 Moment 对象,并且我想在编写<TValue>时排除这种类型的函数将毫无问题地工作。有没有办法使用Typescript来做到这一点,或者唯一的方法是在运行时运行检查?我可以使用 2 种类型,其中第二种是排除 Moment 类型属性的类型,如下所示

type Variants = {
value: TValue,
date: moment.Moment
}
type ExcludeDate = Exclude {typeof Variants, "date"} 

但我想知道是否有另一种方法可以做到这一点。谢谢!我是打字稿的新手,所以如果我不是很清楚,我很抱歉。

您可以按条件类型排除类型:

type MomentType = { x: string } // just an example simulation of moment
function set<TValue>(
key: string,
value: TValue extends MomentType ? never : TValue, // pay attention here
...keySuffixes: string[]
) {
// implementation
}
set('key', { x: 'a' }) // error as its the MomentType
set('key', { y: 'a' }) // ok as its not the MomentType

关键行是value: TValue extends MomentType ? never : TValue.我们说如果传递的类型扩展了我们的MomentType那么该值的类型为never,这意味着您不能将值传递给它,因为 never 是空类型(没有 never 的实例(。

MomentType仅用于示例目的,它可以是您要排除的任何其他类型。

相关内容

最新更新