Hi there! I'm new to TypeScript and encountered an 'Object may be null' error in a function. The function is meant to add two LinkedLists together, each representing numbers (with each digit as its own node), and return a new LinkedList. Can someone help me understand why this error is occurring?
Here is the error message:
Line 33: Char 12: error TS2531: Object is possibly 'null'.
Line 33: Char 35: error TS2531: Object is possibly 'null'.
Line 35: Char 24: error TS2531: Object is possibly 'null'.
Line 36: Char 24: error TS2531: Object is possibly 'null'.
Below is the function code:
// Definition for singly-linked list.
// class ListNode {
// val: number
// next: ListNode | null
// constructor(val?: number, next?: ListNode | null) {
// this.val = (val===undefined ? 0 : val)
// this.next = (next===undefined ? null : next)
// }
//}
//
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let carry = 0;
let cNode1 : ListNode | null = l1;
let cNode2 : ListNode | null = l2;
let returnNode : ListNode | null= new ListNode(0 , null);
let cNode3 : ListNode | null = returnNode;
while(cNode3 != null){
let cVal1 = 0;
let cVal2 = 0;
if(cNode1 != null) cVal1 = cNode1.val;
if(cNode2 != null) cVal2 = cNode2.val;
let cVal = (cVal1 + cVal2 + carry);
let resultingVal = cVal % 10;
carry = Math.floor(cVal / 10);
cNode3.val = resultingVal;
if(cNode1.next != null || cNode2.next != null || carry > 0){
cNode3.next = new ListNode(0 , null);
cNode1 = cNode1.next;
cNode2 = cNode2.next;
}
cNode3 = cNode3.next;
}
return returnNode;
};
The statement causing the error on line 33 is:
if(cNode1.next != null || cNode2.next != null || carry > 0){