Typescript Intersection Types Explained
I've been playing around with types of intersections, and would I expect what follows to work?
Can anyone 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'.
source to share
As others have pointed out, it seems you want union types (c |
). Check out the docs on extended types and use the online REPL to test theories.
Here's some code that uses interfaces and connection types to get the flex number / line 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 expose a use case for intersections, but it looks like you just need a specialization that includes type guards, 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 the crossroads, try to reproduce the extension function to create mixins , but do it with your error domain. Try to serialize errors / loggable / printable etc. Then mix a simple error object (with just a string or something) with an object that can be logged (like the ConsoleLogger example).
source to share
The problem is what SomeResponse
this type has for code
:
number & string
And this is impossible.
You can check this is pretty easy to playground with your code :
let test = response.error.code;
Type test
- number & string
(just hover your mouse over the variable name)
source to share