Typescript Intersection with shared properties

Viewed 173

I'm trying to understand Typescript interfaces better.

I've defined the following interfaces:

interface Bob<T> { 
  x : number; 
  y : string;
  z? : T;
}

interface Jennie<T> { 
  x : number; 
  y : number;
  q : number;
  z? : T;
}

Next I've created this variable:

let myIntersection : Bob<string> & Jennie<number> = {
  x: 20, y: 'hi', q: 30, z: 20
}
    
console.log(myIntersection);

This throws an error:

  solution.ts:3:3
3   y : string;
    ~
The expected type comes from property 'y' which is declared here on type 'Bob<string> & Jennie<number>'solution.ts:49:24 - error TS2322: Type 'number' is not assignable to type 'never'.

I understand that in principle the idea is that the & will combine the properties of both Bob and Jennie and create a new type so if Bob has properties x, y and Jennie has properties a, b - Bob & Jennie will have x,y,a,b - but how does this work in more complex situations like the one above where we have:

  1. the same property defined in both Bob and Jennie but with different types (y)
  2. the optional z property which is string in Bob and number in Jennie

Are there some general rules which are followed in this case or is my code invalid?

0 Answers
Related