user4491949
user4491949

Reputation:

Typescript - how can a exclude a type from a generic type without using Exclude<>?

I have a function that stores different values into the local storage by stringifying them and I want to limit the function from being able to work with Moment objects. The syntax would be this:

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

The thing is the function would work without any issues if the second argument would be a Moment object and I want to exclude this type when writing <TValue>. Is there a way to do this using Typescript or the only way to go is running a check on run-time? I could work with 2 types, where the second would be a type that excludes the property of type Moment, like so

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

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

but I was wondering if there's another way to do it. Thank you! I am new to Typescript so I am sorry if I wasn't very clear.

Upvotes: 1

Views: 1133

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20162

You can exclude type by conditional type:

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

The key line is value: TValue extends MomentType ? never : TValue. We say that if passed type extends our MomentType then the value is of the type never, what means you cannot pass value to it, as never is empty type (there is no instance of never).

MomentType was used only for example purposes, it can be any other type you want to exclude.

Upvotes: 1

Related Questions