Home > Mobile >  How to make two objects intelligently type-consistent throughout in typescript?
How to make two objects intelligently type-consistent throughout in typescript?

Time:10-20

I have two objects of unknown type but guaranteed to be of equal type, how do I declare them?

type Param = number[] | Record<string, string>

function test(a:Param, b:Param) {
    if (Array.isArray(a)) {
        //now a is number[], b is Param, how can I improve my declaration so that b can be inferred as number[] and not use typeof a in here?
    } else if () {
        //
    }
}

CodePudding user response:

Possibly not the most elegant solution, but I was able to get this to work using type inferencing & an additional type guard:

type Param = number[] | Record<string, string>    
type NumParams = [number[], number[]];
type RecordParams = [Record<string, string>, Record<string, string>];

function isNumParams(params: [Param, Param]): params is NumParams {
    return Array.isArray(params[0]);
}

function test(...params: NumParams | RecordParams) {
    if (isNumParams(params)) {
        let [a, b] = params;
        // a & b are number[] here
    } else {
        let [a, b] = params;
        // a & b are Record<string, string> here
    }
}

function test2() {

    var a1: number[] = [];
    var a2: Record<string, string> = {};
    var b1: number[] = [];
    var b2: Record<string,string> = {};

    test(a1, b1); // compiles
    test(a1, b2); // type conflict
    test(a2, b1); // type conflict
    test(a2, b2); // compiles
}
  • Related