Seamy
Seamy

Reputation: 307

Finding property value by string getting

Hey I am having an issue looking up strings in a class based on class properties in typescript.

export class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

I looked online and it says to just use something like eventName['LOGIN'];

However this returns the following error

Element implicitly has an 'any' type because type 'typeof EventName' has no index signature.

I then tried adding in [key: string]: any; But this still gives me the same error. I was wondering could someone please point me to the issue here thanks?

Upvotes: 0

Views: 75

Answers (1)

Fenton
Fenton

Reputation: 250922

If you attempt your example eventName['LOGIN']; using an instance of the EventName class, you'll get that error (if you are using --noImplicitAny):

class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

const eventName = new EventName();

// Element implicitly has an 'any' type because type 'EventName' has no index signature.
const logout = eventName['LOGOUT'];

This is because the properties are static and don't belong to an instance - so you can use:

class EventName {
   public static LOGIN = "LOGIN";
   public static LOGOUT = "LOGOUT";
}

// login: string;
const login = EventName['LOGIN'];

This might be a good example of why the --noImplicitAny flag is terribly useful.

Upvotes: 1

Related Questions