I am trying to understand why TypeScript does not explicitly show a never type in the error messages when intersecting an object type with a string type. Here is my code:
type Test1 = {
b: number;
c: string;
} & string;
// Type '{ b: number; c: string; }' is not assignable to type 'Test1'.
// Type '{ b: number; c: string; }' is not assignable to type 'string'.
let test1: Test1 = {
b: 1,
c: 'c',
}
// Type 'string' is not assignable to type 'Test1'.
// Type 'string' is not assignable to type '{ b: number; c: string; }'.
let test1: Test1 = 'test1'
In the above code, Test1 is defined as an intersection of an object type and string. According to my understanding, this should result in a never type because no value can be both an object with properties b
and c
and a string at the same time.
- When trying to assign an object to test1, I get:
Type '{ b: number; c: string; }' is not assignable to type 'Test1'.
Type '{ b: number; c: string; }' is not assignable to type 'string'.
- When trying to assign a string to test1, I get:
Type 'string' is not assignable to type 'Test1'.
Type 'string' is not assignable to type '{ b: number; c: string; }'.
From my understanding, these should indicate that Test1 is effectively a never type, but TypeScript does not seem to mention never in the error messages. Is this a bug in TypeScript, or is there something I’m missing in how TypeScript handles such intersections?
Any clarification on this behavior would be appreciated. Thank you!
Ansel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.