【问题标题】:Typescript - how can a exclude a type from a generic type without using Exclude<>?Typescript - 如何在不使用 Exclude<> 的情况下从泛型类型中排除类型?
【发布时间】:2020-01-10 09:48:48
【问题描述】:

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

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

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

type Variants = {
   value: TValue,
   date: moment.Moment
}

type ExcludeDate = Exclude {typeof Variants, "date"} 

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

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    您可以通过条件类型排除类型:

    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 仅用于示例目的,它可以是您想要排除的任何其他类型。

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2013-02-03
      • 1970-01-01
      相关资源
      最近更新 更多