TypeScript: correct way to do string equality?

Typescript

Typescript Problem Overview


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.

Typescript Solutions


Solution 1 - Typescript

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.

Solution 2 - Typescript

Use below code for string comparison

if(x === y) {

} else {

}

Solution 3 - Typescript

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHeinrich SchmetterlingView Question on Stackoverflow
Solution 1 - TypescriptssubeView Answer on Stackoverflow
Solution 2 - TypescriptNikhilView Answer on Stackoverflow
Solution 3 - Typescripttamer badawyView Answer on Stackoverflow