Convince me I am wrong: This should not be a type error, right? - I asserted it’s an object - I am using `?.` for property access www.typescriptlang.org/play/#code/G...
5 likes 11 replies
Replies
William O'Connell · Jul 10
Does it work if you change unknown to any?
Tim Fish · Jul 10
It's because `object` doesn't have any properties. www.typescriptlang.org/play/#code/G...
Zak · Jul 15
I feel the benefits are mostly in the signals: I use type errors when renaming or removing properties to know what code to update. If `obj?.a` is always valid, I lose those signals. New devs might use `?` as a crutch when property access fails. Typos like `obj?.a` vs `obj?.A` won’t be caught.
Lionis 🦁 · Jul 10
I think the reasoning here is that object does not have any keys, and you must have a declared type to avoid typos. You could just as easily have typed obj?.aa
Brawaru ☕ · Jul 10
iirc in typescript object just stands for any non-primitive type, but doesn't convey any information about the object shape itself. though yeah, this case seems annoying you could do `v && 'a' in v && typeof v.a !== 'string'`. that `in` will intersect the object type with `{ a: unknown }`
Felds · Jul 10
I had this "problem" just last week. TS only allow property access for known properties, even when it's optional. In other words, even though `null?.a` is valid, TS is saying `null` doesn't have a known property `a`.
John Schulz · Jul 10
On my phone so I can't check, but I think null (and some others?) are typeof object
Jack Franklin · Jul 10
`typeof null === 'object'` so I think you might need to check for null. And then I tend to find 'a' in x more reliable in TS
tiedoton · Jul 10
Curiously the error message is better when using v['a'] instead of v.a. Then it just straight out says "Property 'a' does not exist on type '{}'."
Erin · Jul 10
Hey while you’re fixing TypeScript can you get them to let me skip writing `Promise<>` around the return types of functions that already have the `async` keyword?
Federico Biccheddu · Jul 10
Object check in TS is a PITA. I started parsing them at the edge of the program (app code). This is probably different for lib code. IDK if you're searching for a solution; if so, this is the approach I was using before: www.typescriptlang.org/play/#code/G...