Home > Mobile >  How is it possible to get the right type from a union
How is it possible to get the right type from a union

Time:07-31

Hi i try to write a generic type which get a union. The property extension hold all available strings as union, so far so good this works. But getting the params is not possible, cause it is a union of TypeA | TypeB.

How is it possible to get the write type at the params property depending on the extension property?

here is my current code

type TypeA = {
    someRandomStuff: {
        name: 'tom'
    }
}

type TypeB = {
    doWrite: {
        path: '/any/path'
    }
}

type Executions<T extends [string, {[key: string]: unknown}]> = {
    extension: T[0];
    params: T[1];
}

function executionListener(exec: Executions<['random',TypeA] | ['write',TypeB]>){
    if(exec.extension === 'random'){ // <- this works pretty good
        const params = exec.params.someRandomStuff; //<- this doesnt work as expected
    }
} 

Thank you

CodePudding user response:

this will work

function executionListener(
  exec: Executions<["random", TypeA]> | Executions<["write", TypeB]>
) {
  if (exec.extension === "random") {
    // <- this works pretty good
    const params = exec.params.someRandomStuff //<- this doesnt work as expected
  }
}

CodePudding user response:

Maybe type guards are what you need:

const isTypeA = (exec: Executions<['random', TypeA] | ['write', TypeB]>): exec is Executions<['random', TypeA]> => {
  return exec.extension === 'random';
};

function executionListener(exec: Executions<['random', TypeA] | ['write', TypeB]>) {
  if (isTypeA(exec)) {
    const params = exec.params.someRandomStuff;
  }
}
  • Related