【问题标题】:How to transform "|" to "&"如何转换“|”到 ”&”
【发布时间】:2021-04-02 18:11:45
【问题描述】:

我在我的项目中使用rematchtypescript。 我想从模型中获取所有 effects function 类型,就像这样。

const models = {
    model1: {
        effects: {
            fn1: () => {},
            fn2: () => {},
        },
    },
    model2: {
        effects: {
            fn3: () => {},
            fn4: () => {},
        },
    },
};

type Result = {
    fn1?: () => void;
    fn2?: () => void;
    fn3?: () => void;
    fn4?: () => void;
};

type Models = typeof models;
type EffectsType = { [key in keyof Models]: Models[key]['effects'] }[keyof Models];

/*
this is result type
type EffectsType = {
    fn1: () => void;
    fn2: () => void;
} | {
    fn3: () => void;
    fn4: () => void;
}

 */

结果是model1 | model2。我要的是model1 & model2

Transform 类型的写法

// how to write this type
type Transform<T extends object> = any;

type obj1 = {
    a: string;
    b: string;
};

type obj2 = {
    b: string;
    c: string;
};

type from = obj1 & obj2;

type result = Transform<from>;

// this is result
type result = obj1 | obj2;

【问题讨论】:

    标签: typescript redux types


    【解决方案1】:

    这可能是也可能不是您想要做的,但如果您想切换 |与 & 然后考虑使用正则表达式。

    您不一定需要为此使用转换函数。

    这是您转换问题的可能解决方案 | &

    通过正则表达式,您可以使用替换功能 ()=().replace("\|","&");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多