简体   繁体   中英

How to transform “|” to “&”

I use rematch and typescript in my project. I want to get all effects function type from a models,like this.

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;
}

 */

Result is model1 | model2 model1 | model2 . What I want is model1 & model2 .

How to write the Transform type

// 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;

This may or not be what you want to do but if you want to switch out the | with & then think about using regex.

You don't necessarily need to use a transform function for this.

this is a possible solution to your question to transform | to &

with regex you can use the replace functionality ()=().replace("\|","&");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM