In JavaScript, plain old objects can take all kinds of abuse. For example you can write:
var obj = {};
var func = new Function() {};
obj[func] = 5; // totally fine
obj[func]; // returns 5
With some creativity you could write a generic class SimpleSet<T>
that might use an object as its backing store in JavaScript or TypeScript. One straightforward way may involve writing something like this:
public add(val: T) {
this._dict[val] = val;
}
Which doesn't work in TypeScript. Why? More permissive versions of add
work, see add2
and add3
.
class SimpleSet<T> {
_dict: Object;
constructor() {
}
// error:
public add(val: T) {
this._dict[val] = val;
}
// no error:
public add2(val: T) {
this._dict[val as any] = val;
}
// no error:
public add3(val: any) {
this._dict[val] = val;
}
}
With add
, two errors appear:
Type 'T' is not assignable to type 'Object[T]'.
Type 'T' cannot be used to index type 'Object'.
"function (){}"
? – Alexander O'Maravar obj = {}; var key1 = {prop1:'val1'}; var key2 = {prop2:'val2'}; obj[key1] = "hello"; console.log(Object.keys(obj));
will log["[object Object]"]
. Loggingobj[key2]
will show "hello" because thetoString()
of both objects are the same. – Heretic Monkeyany
being allowed vsObject
being disallowed as a type. I see now I was under the mistaken belief thatany
means "allow all types", instead of "opt out of type checking." – Simon Sarris