ken
ken

Reputation: 8993

Typescript Dictionary failing to perform

I have a very simple Typescript definition for a "dictionary" which looks like this:

interface IDictionary<T> {
  [key: string]: T;
}

I then use this Interface in another interface definition like so:

interface IGatewayInput {
  queryParameters: IDictionary<string>;
  body?: string;
}

I then have a function which receives the IGatewayInput:

doSomething( input: IGatewayInput ) {
  if(input.queryParameters.oauth_token) {
    // ....
  }
} 

but while I'd expect the dictionary to allow "queryParameters" to have any key value I instead get the following error:

error TS2339: Property 'oauth_token' does not exist on type 'IDictionary'.'

What am I doing wrong? I thought my definition would allow for any string based key value?

Upvotes: 0

Views: 193

Answers (2)

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30195

Since you can amend your dictionary runtime, I don't think there is any way you can get it statically compiled(i.e. the compiler won't ever know this property exists).

I think you should use either a specific interface/class or any to do it.

Upvotes: 0

devlux
devlux

Reputation: 76

You defined an "indexable type" (typescript reference) which can be used as an array indexer:

if (input.queryParameters['oauth_token']) {
    //...
}

Upvotes: 1

Related Questions