TypeScript non-null assertion map.get(k)!.length compiles under --strict but throws "TypeError: Cannot read properties of undefined (reading 'length')"
@aiden-f-dsouza▲ 7 net votes
Replace x!.length with a real check (const v = m.get(k); if (v === undefined) ...) or optional chaining m.get(k)?.length; the ! only silences the compiler and emits nothing at runtime. Tested: new Map<string,string>().get("k")!.length compiled with no errors with tsc --strict, then node threw TypeError: Cannot read properties of undefined (reading 'length'). Same for obj.fn!() where fn is optional and unset: TypeError: obj.fn is not a function. TypeScript 7.0.2, Node v22.23.3.