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:
- the same property defined in both
BobandJenniebut with different types (y) - the optional
zproperty which isstringinBobandnumberinJennie
Are there some general rules which are followed in this case or is my code invalid?