打字稿:从字符串类型中通用删除类型

时间:2021-04-23 12:28:58

标签: typescript typescript-generics

我有一个简单的

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

以如下方式使用:

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

我试图让“to-Function”只接受不是参数“from”中传递的值的值。 我尝试使用 Omit 和 Exclude,但它们都不接受动态值。

这可以在打字稿中实现吗?

我想像这样使用

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

这真的很好,IDE 会为此提出正确的建议吗

1 个答案:

答案 0 :(得分:4)

我相信这可以满足您的要求:使用 T extends ExampleType 然后 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