Type error when assigning across objects with matching shape

Hey there, I'm working on migrating a codebase to TS right now, and I was curious about some behavior I saw from the TS compiler. I'm sorry if something like this has been asked - I tried looking, but wasn't sure what terminology to best use. It looks like if I have two objects with matching types but DIFFERING value types depending on key, because the value of obj2[key] ends up being a union of all possible types, I can't simply assign to obj1[key] with that value. I understand what's going on, though my understanding of when this would come into play is pretty loose. It looks like if I add a condition that does exactly the same thing, but splits off the various types into different blocks of the condition, it works. TS Playground example here: https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gRgKwMoAsCGkoF4oG8BQUUaAXFAM7ABOAlgHYDmA3IVHGQUUQMZmW2MWRAL75hLfNwD2dSlCmIAjGXjJ0mHJ2JkA5CggAbA1J0AaVuzyseuhlKkATOCAg7Wo8fkky5ChACYVRFQMaE1WUigdAHcIYDMLDmsoXiiHKhA3ETEJaVlgKABrCBBybFhECG5gADpi0oAKP38ASlyfAppyVUUAaRLyhv4+anoGFpGqKC6ikqkAMyhQSAX5JWwAPisiKjiAVyo6CoQq2rAqKWBL8Aga9G7ougAFC8gqUBruNCMmpVMKahtHJeeZSKYNAxxablAAMTGhAB5ZqUapDGMAUPCaABqbEtbYpDrI8r1cgAbRoAF0hNNFg0AIRdHr9EANeotfFaHgyYD0PYQGmiIh+RRk+qU8rNMUlaliEFgqAQqE0WFYqBI0moiDozHTXGc1h5OT1EklclUmk0OmM7pKFlskocgncui8uj8wWsK2Kk1YP1ROA6A1cNYIUXiyWIfzSkCykRQQzkaBc0PhmWRgIxuNQDz4IA I suppose in the given example, this works because the compiler then knows exactly what type obj1[key] and obj2[key] are, and can reason about them and confirm it's safe. At the end of the day, I'm just doing the same operation though - is this an example of the compiler not being "smart enough" to understand that they keys between objects are counterparts of one another? Sort of like how I can't narrow a type with .includes because the compiler doesn't "get it"? I'm SURE there's a better way to represent this to the compiler - does anyone have advice on how to do that? Thank you so much for taking the time to read this.
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server