I have this snippet
class J {
constructor(public foo: number) {}
}
class B {
constructor(public bar: string) {}
}
interface Cache {
json?: J;
binary?: B;
}
function test(key: "json" | "binary", data: J | B, obj: Cache) {
obj[key] = data;
}
If you try this code in https://www.typescriptlang.org/play/, the line obj[key] = data; is having the following error
Type 'J | B' is not assignable to type 'J & B'. Type 'J' is not assignable to type 'J & B'. Property 'bar' is missing in type 'J' but required in type 'B'.
There's obviously something I am missing but I can't figure out what. Any idea?