1

Looking at this Typescript code :

class A {

} 

let a = new A();
let s: symbol = Symbol('sym');

a[s] = 2;
a[s] = 'f';
a[s] = new Date();

//no errors

We can see that same symboled property is referencing to a difference types .

Question:

Is it possible to use the symbol and yet , get TS type safety ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

2

If you turn on noImplicitAny, you'll get errors on all three assignments because the symbol property is not declared and A does not have an index signature. You can declare the property as follows:

const s: unique symbol = Symbol('sym');
class A {
  [s]: number;
}

let a = new A();

a[s] = 2;  // OK
a[s] = 'f';  // Error
a[s] = new Date();  // Error

(Note, it's a little bit of a lie to call Symbol('sym') a unique symbol. Consider using Symbol() instead. I remember seeing an issue discussing this but I can't find it now.)

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75
0

TS1023: An index signature parameter type must be 'string' or 'number'.

Seem like the key of your class has to be a string or number.

class A {
  [key: symbol]: any; // invalid
} 

Do you look for something like this?

class A {
  [key: string]: number | string | Date;
  [key: number]: number | string | Date;
}

const a = new A();
const s: symbol = Symbol('sym');

a[s] = 2;
a[s] = 'f';
a[s] = new Date();
sevic
  • 879
  • 11
  • 36