Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of Typescript's intersection types

i was playing around with intersection types and i would expect following as working?

Could someone shed some light on it?

type SomeError = {    
    message: string;
    code?: number;    
};

type SomeResponse = {
    error: SomeError & { code: string; }
};

const response: SomeResponse = {
    error: {
        message: 'neco',
        code: 'a'
    } 
};

// Type 'string' is not assignable to type 'number'.

const response2: SomeResponse = {
    error: {
        message: 'neco',
        code: 50
    } 
};

// Type 'number' is not assignable to type 'string'.
like image 427
Tomas Ovesny Avatar asked Nov 30 '25 01:11

Tomas Ovesny


2 Answers

As others have pointed out, it seems you want union types (with the |). Check out the docs on advanced types and use the online REPL to test out theories.

Here's code that uses interfaces and union types to get a flexible number / string code in your error type.

interface SomeError {    
    message: string;
    code: number | string;    
};

interface SomeResponse {
    error: SomeError
}

const response: SomeResponse = {
    error: {
        message: 'neco',
        code: 'a'
    } 
};

const response2: SomeResponse = {
    error: {
        message: 'neco',
        code: 50
    } 
};

The docs lay out a use case for intersections, but it seems you just want specialization, which is where type guards come in, consider this function:

const printErrCode = (code: string | number) => {
    if(typeof code === "string") {
        console.error(code);
    } else {
        console.error(`Err code: ${code}`);
    }
}

Edit: if you want to play with intersection, try replicating the extend function to create mixins, but do it with your error domain. Try to make error serialization / loggable / printable etc. And then mixin a plain error object (with just a string or something) with an object that can log (like the example of ConsoleLogger).

like image 180
Sean Newell Avatar answered Dec 02 '25 04:12

Sean Newell


The issue is that SomeResponse has this type for code:

number & string

And that's impossible to have.

You can check that this is the case quite easily in playground with your code:

let test = response.error.code;

The type of test is number & string (just hover over the variable name)

like image 22
Nitzan Tomer Avatar answered Dec 02 '25 04:12

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!