r create vector of zeros – R: Create vector of zeros

Creating vector of zeros in R.

r create vector of zeros: In this article we will see how to create vector of zeros in Python. Mainly we will see three different ways to create vector of zero.

  1. Using integer() function
  2. Using numeric() function
  3. Using rep() function

Sometimes vector of zeros is required in initializing a vector with values and neutralizing it after performing some operations. So let’s see the three different ways how it actually works.

Method-1 : Creating a vector of zeros using integer () function :

zeros in r: In R the integer() function creates objects of vector(integer) of specified length in the argument but each element of vector is 0.

Syntax-integer (length)

Where,

  • length : It represents the length of the vector

Below is the code example of this.

#Program :

# length of vector is 6
zero_vector = integer(6)
cat(" Using integer() function vector of zeros created: " , zero_vector , "\n")
Output :
Using integer() function vector of zeros created:  0 0 0 0 0 0

Method-2 : Creating a vector of zeros using the numeric() function :

Like integer() function in R, the numeric() function creates object of numeric type and it creates double precision vector of the specified length by the argument where all the elements value equal to zero.

Below is the code example of this.

#Program :

# length of vector is 6
zero_vector = numeric(6)
cat("Using numeric() function vector of zeros created: " , zero_vector , "\n")
Output :
Using numeric() function vector of zeros created:  0 0 0 0 0 0

Method-3 : Creating a vector of zeros using the rep() function :

rep() function in R actually replicates the values of the vectors.

Syntax-rep(v, no_of_times)

Where,

  • v : It represents a vector or a factor
  • no_of_time : It represents the number of times each element of the vector to be repeated

Below is the code example of this.

#Program :

zero_vector = rep(0, 6)
cat(" Using rep() function vector of zeros created: " , zero_vector , "\n")
Output :
Using rep() function vector of zeros created:  0 0 0 0 0 0

 

C program to efficiently multiply a number with 7 using bitwise operator

C program to efficiently multiply a number with 7 using bitwise operator
  • Write a program in C to multiply a number with 7 using bitwise operator.
  • How to multiply a number by 7 in one line.

Required knowledge Bitwise operator in C

    • Let’s derive an expression to multiply a number with 7 using bitwise operator. Let N be the number that we want to multiply with 7.
    • N x 7 = N + N + N + N + N + N + N
    • N x 7 = N + N + N + N + N + N + N + (N – N)
    • N x 7 = (N + N + N + N + N + N + N + N) – N
    • N x 7 = 8xN – N
    • As we know that, left shifting any number by one bit multiply it by 2. Hence, multiplying any number with 8 is equivalent to right shifting it by 3 bits(For Example : NX3 = N << 3). Replacing 8xN in above statement by 8 << 3.

N x 7 = (N << 3) – N

WARNING !!!!
Multiply using bitwise operators: This approach can only be used to multiply integers or char by 7 because bitwise Operators can only be applied on char and integer operands. We cannot use bitwise operators with float, double, long double, void and other user define complex data types.

C program to multiply a number with 7 using bitwise operator.

C program to efficiently multiply a number with 7 using bitwise operator

#include<stdio.h>
 
int main() {
    int num;
     
    printf("Enter an integer\n");
    scanf("%d", &num);
     
    printf("7 X %d = %d", num, (num << 3) - num);
 
    return 0;
}

Output

Enter an integer
3
3 X 7 = 21
Enter an integer
0
0 X 7 = 0

How to fix unexpected end of json input – How to Fix Unexpected end of JSON input Error in JavaScript?

How to Fix Unexpected end of JSON input Error in JavaScript

How to fix unexpected end of json input: When attempting to parse invalid JSON using the JSON.parse or $.parseJSON functions, the “Unexpected end of JSON input” error occurs.

The issue arises while attempting to parse a value such as an empty array or string. To fix the issue, make sure the JSON is valid before parsing it.

Passing an Empty Array or String to the JSON.parse

index.html:

// Pass an empty array to the JSON.parse() function
// and print the result
console.log(JSON.parse([]));

// Pass an empty string to the JSON.parse() function
// and print the result
console.log(JSON.parse(''));

// Here in both the cases SyntaxError: Unexpected end of JSON
// input occurs

Output:

undefined:1


SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/tmp/ER7rLDlJor.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we got the error after passing an empty array and an empty string  
to the JSON.parse function. 
The same thing would happen if you used the $.parseJSON function.

Passing an Empty Array or String to the $.parseJSON() Function

// Pass an empty string to the $.parseJSON() function
// and print the result
// Here we get an error
console.log($.parseJSON(''));

Explanation:

The error occurs because we are attempting to parse invalid JSON.

The error also arises if you attempt to parse an empty server response or if your server fails to send the relevant CORS headers with the response.

If your server returns an empty response and you attempt to parse it, you will receive an error. You should delete the parsing logic in this situation.

If you’re getting the value from your server, ensure sure the server is setting Content-Type header to application/json.

Fixing Unexpected end of JSON input Error in JavaScript

Json parse unexpected end of input: The “Unexpected end of JSON input” error can be resolved in three ways:

  • In a try/catch block, wrap your parsing logic.
  • Ensure that your server returns a valid JSON response
  • If you expect an empty server response, remove the parsing logic from your code.

NOTE:

You may inspect your server's response by opening your developer tools
 and selecting the Network tab. 
The server's response can be viewed by clicking the Response tab.

Using try/catch Blocks to Avoid Error

index.html:

// Use try-catch blocks to avoid "Unexpected end of JSON input"
// error
try {
  // Pass an empty string to the JSON.parse() function
 // and store it in a variable
  const rslt = JSON.parse('');
  // Print the above result 
  console.log(rslt);
} 
// Handle the "Unexpected end of JSON input" Error inside the 
// catch block
catch (error) {
  // If the error occurs the print some random text and
  // corresponding error
  console.log('Sorry There is an Error!!!!\n', error);
}

Output:

Sorry There is an Error!!!!
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/tmp/ER7rLDlJor.js:6:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

If the JSON.parse() function returns an error as a result of parsing invalid JSON, the error is given as a parameter to the catch function, where it can be handled.

If you know the server’s response does not include valid JSON, you can delete/remove the call to the JSON.parse function.

You can also use an online JSON validator to determine whether a JSON string is valid.

 

Property does not exist on type – How to Fix Property does not exist on type Object in TypeScript?

How to Fix Property does not exist on type Object in TypeScript

Property does not exist on type: When we try to access a property that is not contained in the object’s type, we get the “Property does not exist on type Object” error.

To fix the error, explicitly type the object properties or use a type with variable key names.

Let us see an example to know how this error occurs

index.ts:

// Create an object and store it in a variable
const gvn_obj: Object = {
  EmpId: 6136,
  EmpName: 'John',
};

// Here the key salary does not exist on the above created object 'gvn_obj'
// So, when we try to access it we get a Property 'salary' does 
// not exist on type 'Object' Error.
gvn_obj.salary = 50000;

Output:

script.ts(10,9): error TS2339: Property 'salary' does not exist on type 'Object'.

Explanation:

Here we typed the gvn_obj variable as Object and tried to access the salary property on the object.

The salaryproperty, however, does not exist on the Object type, therefore the type checker returns an error.

Fixing Property does not exist on type Object Error in TypeScript

1)When you know property names ahead of time

// This is the case when you know property names ahead of time
// Give the type(datatypes) of property names (variable)
type FirstEmploy = {
  EmpName: string;
  EmpId: number;
  salary?: number;
};

// Create an object for the above type object 
const object_1: FirstEmploy = {
  EmpName: 'Alex',
  EmpId: 8459,
};

// Add a new key value value(here salary) to the above object using optional chaining(.) 
object_1.salary = 50000;

// Print the above object
console.log(object_1);

Output:

{ EmpName: 'Alex', EmpId: 8459, salary: 50000 }

Explanation:

  • Here it shows how to type an object when you know the property names and the types of the values ahead of time.
  • You can use a question mark(?) to indicate properties that you will not provide when initializing the object.
  • Now that the salary property exists in the object’s type, we can securely access it.

2)When you DON’T know All the property names ahead of time

You may not know the names of all of the object’s keys or the shape of the values ahead of time in some scenarios.

index.ts:

// This is the case when you don't know all the 
// property names ahead of time
type SecondEmploy  = {
  // we will use any if we dont know the type of variable
  [key: string]: any; 
  EmpName: string;
};

const object_2: SecondEmploy = {
  EmpName: 'Michel',
};
// Add the address field to the above created object using the optional chaining(.) operator
object_2.Address = 'Hyderabad';
object_2.EmpId = 2468;

// Print the above object
console.log(object_2);

Output:

{ EmpName: 'Michel', Address: 'Hyderabad', EmpId: 2468 }

Explanation:

The {[key: string]: any} syntax is known as an index signature, and it is used when the names of the object’s keys or the shape of the values are unknown ahead of time.

The syntax simply says that when the object is indexed with a string key, it will return a value of any type.

NOTE:

If you know any of the names of the properties ahead of time, you can specify them to improve type safety.

In the SecondEmploy type, we set the EmpName property to string so that the type checker would throw an error if the property was not provided or was set to a value of a different type.

You can use a more particular index signature for improved type safety if you don’t know the names of all of the object’s keys but know the shape of the values.

index.ts:

type SecondEmploy   = {
  [key: string]: string | number;
  EmpName: string;
  EmpId: number;
};

const object_2: SecondEmploy   = {
  EmpName: 'Michel',
  EmpId: 4586,
};

object_2.salary = 50000;
object_2.EmpAddress = 'Hyderabad';

console.log(object_2)

Output:

{
EmpName: 'Michel',
EmpId: 4586,
salary: 50000,
EmpAddress: 'Hyderabad'
}

The index signature in the preceding example indicates that when the object is indexed with a string key, it will return a value of type string or number.

In TypeScript, the string | number syntax is referred to as a union type.

Because the EmpName and EmpId properties are both strings and return distinct types, we had to utilize a union type.

In other words, you cannot specify that when the object is indexed with a string key, it returns a string value (type string) and then add another string key to the interface with a numeric value (type number).

index.ts:

type SecondEmploy = {
  [key: string]: string;
  EmpName: string;
  
  // Here we get an error i.e., Property 'EmpId' of type 'number' is not
  // assignable to string index type 'string'
  EmpId: number;
};

Output:

script.ts(7,3): error TS2411: Property 'EmpId' of type 'number' is not assignable to string index type 'string'.

 

Filter dictionary by value python – Python : Filter a dictionary by conditions on keys or values

How to filter a dictionary by conditions on keys or values in python ?

Filter dictionary by value python: This article is about the filtration of a dictionary according to arbitrary condition on key or values or on both where key is the name and value is the content.

As we know in python we express a dictionary as a pair (key:value) where values can be any data type and keys can be string, number or tuple, values can repeat but keys must be unique and immutable.

Now, for better understanding take an example

We have a dictionary named student_details contains keys and values.

student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}

Here, int type elements are keys and string type elements are values

Student_details[1] = Name
Student_details[2] = RollNo
Student_details[3] = Collage_Name
Student_details[4] = Branch
Student_details[5] = Mobile_No
Student_details[6] = City
Student_details[7] = State
Student_details[8] = Pincode
Student_details[9] = Address
Student_details[10] = Registration_No

Method-1 : Filter a Dictionary by conditions :

Filter a Dictionary by keys in Python :

Python filter dictionary by key: We can filter the above dictionary by condition like the keys are even or the keys are prime or keys are odd.

Let’s filter above dictionary by keeping only elements whose keys are odd.

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep keys which are odd
  if ((key % 2) != 0):
    new_student_details[key] = value

print("New dictionary:")
print(new_student_details)
Output:
New dictionary:
{1: 'Name', 3: 'Collage_Name', 5: 'Mobile_No', 7: 'State', 9: 'Address'}

Here, new_student_details is the null dictionary which contains the element whose key is odd by making iteration of the items of new_student_details. We can also filter a dictionary by value fields.
Note : Like that by giving any arbitrary condition to the original dictionary, we can get the required new dictionary.

Filter a Dictionary by values in Python :

Filter dictionary python: Like keys, we can also filter the dictionary by putting the condition in values.

Let’s filter above dictionary by keeping only elelemnts whose values length >= 7.

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'College_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep values whose length >=7
  if ((len(value) >= 7)):
    new_student_details[key] = value

print("New dictionary:")
print(new_student_details)
Output :
New dictionary :
{3: 'College_Name, 5: 'Mobile_No, 8: 'Pincode', 9: 'Address', 10: 'Registration_No'}

Method-2 : Filter a Dictionary by filter() method :

Filtering dictionary by key python: As we all know python has many pre-define functions. So we can use pre-define function i.e filter() instead of making your own.

  • filter() method
    * It is a built-in function
    * Returns boolean values i.e True or False
    * Filtered through a function to test if the item is accepted or not.
    * An iterable sequence to be filtered

Let’s try filter() to do conditional filteration on the same dictionary by keeping the elements whose keys are divisible by 2 i.e

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Checking the condition which keys are even
new_dict=dict(filter(lambda elem: elem[0] % 2 == 0,student_details.items()))

print("New dictionary:")
print(new_dict)
Output :
New dictionary :
{2: 'RollNo' , 4: 'Branch' ,  6: 'City' , 8: 'Pincode' , 10: 'Registration_No'}

Here we filtered elements based on the keys , similarly we can put conditions on values also and we can filter the dictionary.

Method -3 : Filter a Dictionary by Dict Comprehension :

Python dictionary filter: Let’s try filteration of a dictionary by keeping the elements whose keys are divisible by 2 i.e

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
#Iterate all over the items in dictionary
new_dict = {key: value for key, value in student_details.items() if key%2==0}
print("Filtered dictionary:")
print(new_dict)
Output :
Filtered dictionary:
{2: 'RollNo' , 4: 'Branch' ,  6: 'City' , 8: 'Pincode' , 10: 'Registration_No'}

Let’s overview the complete program :

#Program :

#dictionary
student_details={1: 'Name' , 2: 'RollNo' , 3: 'Collage_Name' , 4: 'Branch' , 5: 'Mobile_No' , 6: 'City' , 7: 'State' , 8: 'Pincode' , 9: 'Address' , 10: 'Registration_No'}
new_student_details=dict()
# Iterate over all the items in dictionary
for (key,value) in student_details.items():
#Conditional statement
#only keep keys which is divisible by 2
    if ((key % 2) != 0):
        new_student_details[key] = value

print("New dictionary:")
print(new_student_details)

#Filter check the key is even or not and pair to the new dictionary
new_dict=dict(filter(lambda elem: elem[0] % 2 == 0,student_details.items()))
print("Filtered dictionary:")
print(new_dict)

# Iterate over all the items in dictionary and check the key is even or not and pair to the filtered dictionary
filtered_dict = {key: value for key, value in student_details.items() if key%2==0}
print("Filtered dictionary:")
print(filtered_dict)
Output:
New dictionary:
{1: 'Name', 3: 'Collage_Name', 5: 'Mobile_No', 7: 'State', 9: 'Address'}
Filtered dictionary:
{2: 'RollNo', 4: 'Branch', 6: 'City', 8: 'Pincode', 10: 'Registration_No'}
Filtered dictionary:
{2: 'RollNo', 4: 'Branch', 6: 'City', 8: 'Pincode', 10: 'Registration_No'}

C++ sort lambda – C++ : How to Sort a List of Objects with Custom Comparator or Lambda Function

C++ sort lambda: In the previous article, we have discussed about Different ways to Initialize a list in C++. Let us learn how to Sort a List of Objects with Custom Comparator or Lambda Function in C++ Program.

Sorting a List of Objects with Custom Comparator or Lambda Function

Std sort lambda: In this article, we will learn different ways of sorting a std::list of user defined data types with custom comparators and lambda function.

Let we have a Student type that contains roll and name.

struct Student

{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

This student type has < operator which compares two student using < on roll field. Now, let’s create list of Student Objects,

std::list<Student> list_Students = { Student(15, "Aditya"),

                                    Student(6, "Sujeet"),

                                    Student(41, "Arhan"),

                                    Student(28, "Dipti"),

                                    Student(3, "Tamanna"),};

Now, let’s sort list of Students using std::list::sort.

std::list::sort

Custom sort c++: It has two different overloaded versions i.e.

void std::list::sort(); 
// Will use default sorting criteria and will compare using < operator
template <class Compare>
void sort (Compare comparator);
//Accepts compare function or function object and using comparator it will sort

Sorting a List with Default Criteria :

Sort a list c++: We can sort a list with default criteria i.e. < operator of type which doesn’t accept any arguments. i.e. list_Students.sort();.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // List being sorted by default criteria
    list_Students.sort();
    std::cout<<"After sorting students based on roll : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on roll :

3 :: Tamanna

6 :: Sujeet

15 :: Aditya

28 :: Dipti

41 :: Arhan

Sorting a List of Objects with Custom Comparator & Function Object :

C++ custom sort: There is another overloaded version of std::list::sort which accepts function pointer as an argument and compare while implementing sorting i.e.

template <class Compare>

void sort (Compare studcomp);

Then we will define a function object or comparator which will compare student list based on their names.

struct StudentComp

{

// Compares 2 Students objects according to their names

bool operator ()(const Student & stud1, const Student & stud2)

{

if(stud1.name == stud2.name)

return stud1 < stud2;

return stud1.name < stud2.name;

}

};


Now the above function will try to sort the list using the names by using list_Students.sort(StudentComp());

Complete program :

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    list_Students.sort(StudentComp());
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna

Sorting a List of Objects with Custom Comparator & Lambda Function :

List sort c++: Instead of defining a separate Function object we can sort the list of students by using Lambda function by passing lambda function in sort() as argument.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // Sort student list using Lambda function
    list_Students.sort([](const Student & stud1, const Student & stud2)
        {
            if(stud1.name == stud2.name)
                return stud1 < stud2;
            return stud1.name < stud2.name;
        });
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna

ts object is possibly ‘undefined’ – How to Fix Object is possibly ‘undefined’ error in TypeScript

How to Fix Object is possibly 'undefined' error in TypeScript

ts object is possibly ‘undefined’: When we try to access a property on an object that may be undefined, we get the “Object is possibly ‘undefined'” error (example- marked as optional).

To fix the mistake, use optional chaining to short-circuit if the reference is null, such as e?.name?.salary.

index.ts

// Create a class
type Employ = {
  //  Create a nested objects which may be undefined 
  name?: { 
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// When we try to get salary then we get => Error: Object is possibly 'undefined'.ts(2532)
e.name.salary;

Output:

Error: Object is possibly 'undefined'.ts(2532)

The nameproperty on the Employ type is marked as optional, so it may be undefined.

This is why we cannot safely access `address` or salaryproperties.

Fixing Object is possibly ‘undefined’ error in TypeScript

We can fix this error by using theoptional chaining (.) operator.

Method #1: Using Optional Chaining

// Create a class
type Employ = {
// Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ clas
const e: Employ = {};

// Here now we don't get any error.It works fine
const rslt = e?.name?.salary;

Explanation:

There will be NO errors in this case.

In TypeScript, the dot (?.) syntax is known as optional chaining. It is similar to using dot notation to access a nested property of an object, but instead of throwing an error if the reference is nullish (null or undefined), it short-circuits and returns undefined.

This method is typically used for retrieving data from a remote API or reading it from a file, where some of the 
properties may be empty.

Method #2: Using If Conditional Statement

Object is possibly ‘undefined’: We used an if statement to determine whether the e.name property is not equal to undefined or null.

// Create a class
type Employ = {
//  Create a nested objects which may be undefined 
  name?: {
    address?: string;
    salary?: string;
  };
};
// creating an object for the above employ class
const e: Employ = {};

// check if the name property of the employ class is not undefined using the optional chaining(.) and if conditional statement
if (e.name != undefined) {
  console.log(e.name.address?.toUpperCase);
  console.log(e.name.salary?.toUpperCase);
}

Explanation:

There will be NO errors in this case.

TypeScript knows that the e.nameis of type object and not undefined once we enter the if block.

Here we utilized loose not equals (!=) to check for both undefined and null values. You can only use strict not equals (!==) to check for undefined.

Because undefined is identical to null in a loose comparison, it covers both undefined and null.

console.log(undefined == null);  // output => true
console.log(undefined === null); // output => false

Output:

true
false

If you are certain that the property cannot have a null value, you can use the non-null assertion operator.

//  Create a class
type Employ = {
  name?: {
    address?: string;
    salary?: string;
  };
};

const e: Employ = {
  name: {
    address: 'Hyderabad',
    salary: '50000',
  },
};

console.log(e.name!.address); 
console.log(e.name!.salary);

Output:

Hyderabad
50000
  • In TypeScript, the exclamation mark(!) is the non-null assertion operator.
  • It removes null and undefined values from a type without performing any explicit type checking.
  • When you use this method, TypeScript is basically told that this value will never be null or undefined.
  • We used it right after the name property, so TypeScript knows that e.name will never be null or undefined

Method #3: Using Logical AND(&&) Operator

When comparing properties in an if statement, utilize the logical AND (&&) operator to ensure that the property is of the correct type.

// @@@

type Employ = {
  name?: {
    address?: string;
    salary?: number;
  };
};

const e: Employ = {};

if (
  e?.name &&
  typeof e.name.salary === 'string' &&
  e.name.salary > 1000
) {
  console.log('success');
}

Output:

Your program did not output anything!

Explanation:

Here the logical AND (&&) operator ensures that the property name is not undefined, that salary exists on the object and is a number before comparing it to the number 1000.

This is required because if the reference is nullish (null or undefined), the optional chaining operator (?.) would return undefined, and TypeScript does not support comparing undefined to a string.

Cannot find module typescript – How to Fix Cannot find module ‘typescript’ Error in TypeScript

How to Fix Cannot find module 'typescript' Error in TypeScript

Cannot find module typescript: To resolve the cannot find module ‘typescript’ error, run the npm i -g typescript command and build a symbolic link from the globally installed package to node_modules using the npm link typescript command.

Open a terminal in the root directory of your project and run the following commands:

Shell ( Command 1):

// It is use install typescript globally
npm i -g typescript

Output:

added 1 package, and audited 2 packages in 4s
found 0 vulnerabilities

Shell (Command 2):

// To Create an symbolic link from the global typescript package to the node modules of the current folder use below command
npm link typescript

An unhandled exception occurred: cannot find module ‘typescript’: The error should be fixed when you run the above two commands.

If the global TypeScript installation fails, you may need to run the command with sudo.

Run the following command to see if TypeScript has been successfully installed:

shell

tsc --version

The command’s output should show the version of the TypeScript package installed on your machine, for example, 4.8.0.

The npm link command builds a symbolic link from the globally installed package to the current folder’s

node_ modules/ directory.

If the error still persists, try deleting your node_modules and package-lock.json files, re-running npm install, and restart your IDE.

shell:

// The below command is to remove the node_modules and package-lock.json
rm -rf node_modules package-lock.json
// It is use install typescript globally
npm install
// To Create an symbolic link from the global typescript package to the node modules of the current folder use below command
npm link typescript

If the error still continues, be sure to restart your IDE. VSCode frequently crashes, and a reboot occasionally fixes the problem.

NOTE:

If this fails, try installing TypeScript locally.

shell:

// the below command is used to install the typescript and save it on the system
npm install --save-dev typescript

This will add typescript to your project’s development dependencies, eliminating the need to run the link command.

Exports is not defined typescript – How to Fix ReferenceError: exports is not defined in TypeScript?

How to Fix ReferenceError exports is not defined in TypeScript

Exports is not defined typescript: To fix the "Uncaught ReferenceError: exports is not defined" error, add a script tag that declares/defines an exports variable, such as <script> var exports ={} ;</script>above your JS script tag if in the browser, or remove the type attribute if it is set to the module in your package.json file in Node.js.

Fixing ReferenceError: exports is not defined in TypeScript?

Browser – ReferenceError: exports is not defined

Exports is not defined: If you see the error when running code in the browser, try to define a global exports variable above the script tags that load your JavaScript files.

index.html

<script>var exports = {};</script>

<!-- Add the JavaScript script below -->
<script src="index.js"></script>

This will define the exports variable and set it to an empty object, preventing an error from occurring if properties are accessed on it.

Browsers do not support the CommonJS syntax of require and module.exports (without using a tool like webpack), which is creating an error.

If you’re testing your code in the browser, remove the module property from your tsconfig.json file and change the target to es6.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",  // change the targe to es6
    // "module": "commonjs", // Remove this or comment it (if browser env)
  }
}

When you remove the module option and set the target to es6, the imports and exports of your ES6 modules will not be compiled to the older CommonJS syntax that browsers do not support.

Because modern browsers support all ES6 features, ES6 is a suitable choice.

If it doesn’t work, try to set the type attribute to module in your script tags.

index.html

<!-- Set the correct path according to the setup --> 
<script type="module" src="index.js"></script>

And use the ES6 Modules syntax to import and export.

index.ts

import {v4} from 'uuid'
// Create a function which does the product of two arguments provided
export function multiply(a, b) {
  return a * b;
}

Because browsers do not support the CommonJS syntax, setting the module to commonjs in your tsconfig.json instructs TypeScript to emit CommonJS files, which is a very likely cause of the issue.

If you see the error in a Node.js application, consider removing the type attribute from your package.json file if it is set to module.

{
  "type": "module", // remove this liine or comment it
}

When type is set to module, we can no longer use CommonJS’s exports and require syntax and must instead use ES Modules syntax for all imports and exports, which may be causing the error.

This occurs when your package.json file has type set to module but your tsconfig.json file has module set to commonjs.

Because type = module instructs Node.js to utilise ES Modules syntax, while module = commonjs encourages TypeScript to produce CommonJS files, these two options are incompatible.

Examine your tsconfig.json file and make sure it looks like this.

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "esModuleInterop": true,
    "moduleResolution": "node",
    // ... your other options
  }
}

Your target option should be es6 or higher, and your module should be CommonJS.

For imports and exports, make sure to utilize the ES6 modules syntax.

index.ts

import {myDefinedFunction} from './myFile'

export function multiply(a:number, b:number) {
  return a * b;
}

Because Node JS supports the CommonJS syntax, if you use the ES modules syntax and instruct TypeScript to produce CommonJS code by setting module to commonjs, the export above will be compiled to CommonJS and should work.

The only reason it wouldn’t work is that you’re emitting CommonJS files but instructing Node.js to read them using ES6 Module syntax.

 

How to Fix Cannot find module ‘X’ Error in TypeScript?

How to Fix Cannot find module 'X' Error in TypeScript

When TypeScript cannot find a third-party or local module in our project, the "Cannot find module or its matching type declarations" error occurs.

To resolve the error, ensure that the module is installed and that moduleResolution is set to node in your tsconfig.json file.

Check that you have the module installed if it is a third-party module.

shell

// install the required module using the npm install command
npm install module-name
// here it saves the module
npm install --save-dev @types/module-name

NOTE:

In your error message, replace module-name with the name of the module.

If you’re encountering issues with a third-party module, try removing your node-modules and package-lock.json files, re-run npm install, and reload your IDE.

shell:

// remove the node modules using the rd and rm commands and also from package-lock.json
rm -rf node_modules package-lock.json
// run npm install command to install all the modules which are in the package.json
npm install

Reload your IDE, VSCode frequently malfunctions/glitches and requires a reboot.

If it doesn’t work or TypeScript can’t find your local modules, try to set moduleResolution in your tsconfig.json file to node.

tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node",
    // rest of lines
  }
}

More information regarding classic vs node module resolution can be found in the TypeScript documentation.

If it doesn’t work, make sure TypeScript is tracking the module you’re attempting to import. It should be included in your include array and not in your exclude array in your tsconfig.json file.

tsconfig.json

{
  "compilerOptions": {
    // ...
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "src/**/*.spec.ts"]
}

TypeScript will not be able to find the module if it is not in the src directory when using the configuration from the code snippet above.

Check to see that you haven’t already excluded the module by adding it to your exclude array.

If the error message changes to "Could not find declaration file for module'module-name,'” TypeScript has found the module you are attempting to import but cannot locate its type declarations.