Javascript Typescript-如何在不使用exclude<;的情况下从泛型类型中排除类型>;?

Javascript Typescript-如何在不使用exclude<;的情况下从泛型类型中排除类型>;?,javascript,typescript,types,Javascript,Typescript,Types,我有一个函数,通过字符串化将不同的值存储到本地存储器中,我想限制该函数不能处理矩对象。语法如下: public static set<TValue>( key: LocalStorageKeyEnum, value: TValue, ...keySuffixes: string[] ) { localStorage.setItem( LocalStorage.buildKey(key, keySuff

我有一个函数,通过字符串化将不同的值存储到本地存储器中,我想限制该函数不能处理矩对象。语法如下:

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


但我想知道是否有其他方法可以做到这一点。非常感谢。我是Typescript新手,如果我不太清楚,我很抱歉。

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

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
typemomenttype={x:string}//只是一个模拟力矩的示例
函数集(
键:字符串,
value:TValue扩展MomentType?从不:TValue,//注意这里
…keySuffixes:string[]
) {
//实施
}
将('key',{x:'a'})//错误设置为MomentType
set('key',{y:'a'})//确定,因为它不是MomentType
关键行是
value:TValue扩展动量类型?从不:t值
。我们说,如果传递的类型扩展了我们的
MomentType
,那么值的类型是
never
,这意味着您不能将值传递给它,因为never是空类型(没有never的实例)

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

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