Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: correct way to do string equality?

Tags:

typescript

If I know x and y are both of type string, is the correct way to do string equality simply x == y?

The linter I'm using complains about this.

like image 922
Heinrich Schmetterling Avatar asked Jan 04 '15 21:01

Heinrich Schmetterling


People also ask

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

What is === in TypeScript?

The Typescript has two operators for checking equality. One is == (equality operator or loose equality operator) and the other one is === (strict equality operator). Both of these operators check the value of operands for equality.

What is the correct way of checking string equality?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

What is the difference between == and === in TypeScript?

== is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.


Video Answer


2 Answers

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

like image 122
ssube Avatar answered Oct 21 '22 02:10

ssube


Use below code for string comparison

if(x === y) {

} else {

}
like image 3
Nikhil Avatar answered Oct 21 '22 02:10

Nikhil