Typescript 如何使用对象作为键创建词典?

Typescript 如何使用对象作为键创建词典?,typescript,Typescript,我尝试使用对象作为键创建字典: api:{[key:string]:string}={ getItems:'api/v1/items/all' }; 如果我尝试使用它var urlpath=api.getItems我得到: 类型{[key:string]:string上不存在属性“getItems”` } 如果我将键的类型更改为any{[key:any]:string},我会得到: 索引签名参数类型必须为“字符串”或“数字” 我可以这样使用它,但这不是我想要的: var urlpath=api

我尝试使用对象作为键创建字典:

api:{[key:string]:string}={
getItems:'api/v1/items/all'
};
如果我尝试使用它
var urlpath=api.getItems我得到:

类型{[key:string]:string上不存在属性“getItems”` }

如果我将键的类型更改为any
{[key:any]:string}
,我会得到:

索引签名参数类型必须为“字符串”或“数字”

我可以这样使用它,但这不是我想要的:

var urlpath=api['getItems'];
如何使用对象作为键创建字典?

看看这是否有帮助

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


Ajay

您可以使用@basarat创建的名为“typescript集合”的精彩库。请查看以下链接:

您需要的只是使用以下命令安装它:

npm install typescript-collections
它还包含所有必要的定义,以提高代码体验。

解决方案:

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

您必须创建一个包含所有参数(包括getItems)的接口或类。然后将api声明为该类型的对象。如果您现在声明了执行方式,Typescript将无法理解,因为它没有interface@iberbeu您的建议是可行的,不过最好不要使用该界面。你现在知道为什么typesricpt不理解这一点了吗?因为它是一种类型化语言。这意味着您始终需要为每个对象定义一个接口。这实际上就是您在移动到typescript时所要寻找的,即当您尝试按您的方式编写代码时,会收到一条错误消息。如果您仍然想这样做,那么您应该放弃typescript并继续直接使用JS。在我看来,键的类型可以是任何类:
{[key:MyClass]:string}
。在这种情况下,saefty类型仍然适用。如果你知道为什么这不可能,我指的是你。@lambdagreen你可以使用
const-api:any
,但是你没有进行类型检查。