cfischer
cfischer

Reputation: 470

How can I have a dictionary using objects as keys?

I try to have a dictionary using objects as keys:

api: {[key: string]: string} = {
  getItems: 'api/v1/items/all'
};

If I try to use it var urlpath = api.getItems; I get:

Property 'getItems' does not exist on type '{ [key: string]: string;` }.

If I change the key's type to any {[key: any]: string}, I get:

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

I can use it like this, but that's not what I want:

var urlpath = api['getItems'];

How can I have a dictionary using objects as keys?

Upvotes: 4

Views: 6838

Answers (3)

Paleo
Paleo

Reputation: 23692

A solution:

const api: {[key: string]: string; getItems: string} = {
  getItems: 'api/v1/items/all'
};

Indexable types are made in order to be used with the operator []. They enforce type checking with this operator:

api['abc'] = 123; // Type 'number' is not assignable to type 'string'

They don't provide a way to access to any arbitrary member name api.abc.

Upvotes: 0

Ajay
Ajay

Reputation: 4971

See if this helps...

TypescriptDictionary.ts

export interface typescriptDictionary {
    getItems: string;    
    getItem2: string;
}

export class TypescriptDictionary implements typescriptDictionary {

    private _getItems: string;
    private _getItem2: string;

    constructor (item: string, item2: string ) {
          this._getItems = item;
          this._getItem2 = item2;
    }


    public get getItems(): string {
          return this._getItems;
    }

    public get getItem2(): string {
          return this._getItem2;
    }
}

To use TypescriptDictionary.ts, import its interface and class, create a variable of type IfcTypescriptDictionary.ts, initialize it using class constructor and access its different types using same variable.

DemoUsage.ts

import {IfcTypescriptDictionary} from 'filePath';
import {TypescriptDictionary} from 'filePath';

export class UseDemo {

    var dictionary: IfcTypescriptDictionary;

    // initialize it with its class constructor.

    dictionary = new TypescriptDictionary('demo text', 'demo text1');

    // access it using
    console.log(dictionary.getItems);
    console.log(dictionary.getItems2);
}

Regards

Ajay

Upvotes: 0

Andrei Tarutin
Andrei Tarutin

Reputation: 683

You can use the wonderful library created by @basarat and named "typescript-collections". Kindly find the link below: typescript collections

What you need is just install it with the following command:

npm install typescript-collections

It also contains all the necessary definitions just to make code experience better.

Upvotes: 1

Related Questions