Typescript: Generic Removal of Type from string-type

Viewed 32

I have a simple

type ExampleType = 'a' | 'b' | 'c';

which is used in the following way:

from(from: ExampleType) {
    return {
        to: (to: ExampleType) => {
            // move something from/to
        },
    }
}

I am trying to have the "to-Function" only accept values that are not the value passed in the parameter "from". I tried using Omit and Exclude but they both won't accept a dynamic value.

Can this be achieved in typescript?

I want to use it like

move(something).from('a').to('b'); // .to() should only accept 'b' and 'c'

and it would be really nice, would the IDE make the correct suggestions for that

1 Answers

I believe this satisfies what you're looking for: Use T extends ExampleType then Exclude<ExampleType, T>

type ExampleType = 'a' | 'b' | 'c';

const from = <T extends ExampleType>(from: T) => {
    return {
        to: (to: Exclude<ExampleType, T>) => {
            // move something from/to
        },
    }
}

from('a').to('b'); // good
from('a').to('c'); // good
from('a').to('a'); // TypeError

TypeScript Playground

Related