How can I use a dictionary as keys?

I am trying to use a dictionary as keys:

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

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

The 'getItems' property does not exist in the type' {[key: string]: string; `}.

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

The type of the index signature parameter must be "string" or "number".

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

var urlpath = api['getItems'];

How can I use a dictionary as keys?

+4
source share
3 answers

You can use the wonderful library created by @basarat called "typescript -collections". Please find the link below: typescript collections

:

npm install typescript-collections

, .

+1

, ...

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;
    }
}

TypescriptDictionary.ts, , IfcTypescriptDictionary.ts, , .

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);
}

0

:

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

[]. :

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

api.abc.

0

All Articles