【问题标题】:Typescript: Generic Removal of Type from string-type打字稿:从字符串类型中通用删除类型
【发布时间】:2021-07-17 15:54:10
【问题描述】:

我有一个简单的

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 会为此提出正确的建议,那就太好了

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    我相信这可以满足您的需求:使用 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

    【讨论】:

    • 优雅的处理方式!
    • 先生,您是我今天的英雄!周末愉快,非常感谢!
    • 没问题!这是一个很好的问题。我最初不确定这是否可能,所以我也学到了一些东西!
    • 当得到这样的答案时,我意识到我在 Typescript 中有很多东西要学:-)
    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2022-01-03
    • 2019-07-03
    • 2016-10-25
    • 1970-01-01
    • 2018-04-28
    • 2013-01-07
    • 2022-08-09
    相关资源
    最近更新 更多