fimbullinter / wotan

Pluggable TypeScript and JavaScript linter
Apache License 2.0
282 stars 23 forks source link

add rule to disallow non-null assertion after optional chain #749

Open ajafff opened 3 years ago

ajafff commented 3 years ago
declare let obj: {prop: string | null} | undefined;

let a = obj?.prop!; // not allowed: 'a' is inferred as 'string' instead of 'string | undefined'
let b = obj?.prop!.length; // allowed to asssert that a certain property in the chain is not nullish, 'b' is 'number | undefined' as expected

NonNull inside an optional chain is treated special and only asserts that one element in the chain is non-null. Whereas NonNull at the end of an optional chain removes null and undefined from the type of the whole chain. That doesn't make any sense because you wouldn't need an optional chain if you knew everything is non-null.