1

In Python you can do something like this

>>> a = ('a', 'b')
>>> b = ('a', 'b')
>>> a == b
True

However in Typescript

    type test = [string, string];

    var data1: test = ['a', 'b'];
    var data2: test = ['a', 'b'];

    console.log(data1 == data2);    // return false
    console.log(data1 === data2);   // return false

equality check for two data of the same type is using reference, I know I can loop through the array but are there syntactic sugar to check for data equality analogous to Python tuple ?

testing
  • 2,303
  • 4
  • 20
  • 32
  • Nope, sorry. You'll have to resort to comparing each element of the array. I guess that's what TypeScript does for you in the background. http://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript – Nicklas Nygren Apr 18 '16 at 06:17
  • Possible duplicate of [Object comparison in JavaScript](http://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – Amid Apr 18 '16 at 06:19
  • Not a duplicate as this is for Typescript which does automate a lot of stuff - but until / unless they add something like that, pointing at the Javascript answer will answer this – Rycochet Apr 18 '16 at 08:00
  • 1
    you can always add an `equals` method to the `Array` prototype which does this. – Nitzan Tomer Apr 18 '16 at 11:43

3 Answers3

1

Is there a way to automatically check data equality for data type in Typescript?

No. The situation is the same as in JavaScript i.e. you need a library or custom code.

basarat
  • 261,912
  • 58
  • 460
  • 511
1

In practice, the right answer to this is almost always to use Lodash's _.isEqual function:

import _ = require("lodash");

type test = [string, string];

var data1: test = ['a', 'b'];
var data2: test = ['a', 'b'];

console.log(_.isEqual(data1, data2));

This will do deep equality comparisons for you, similarly to what you'd expect coming from other languages.

Tim Perry
  • 11,766
  • 1
  • 57
  • 85
0

TypeScript does not ship this feature off-the-shelf, the situation is completely akin to that encountered in JavaScript: you'll need to recursively scan objects (I believe Python is doing something similar under the hood).

To achieve a quick makeshift comparison for testing purposes, you could convert your values to JSON strings, then compare those strings:

JSON.stringify(data1) == JSON.stringify(data2); // true
John Weisz
  • 30,137
  • 13
  • 89
  • 132