如何使用TypeScript声明属性为字符串类型的对象? [英] How to declare an object whose properties are of type string only using TypeScript?

查看:195
本文介绍了如何使用TypeScript声明属性为字符串类型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中有一个这样的配置数组.

I have a configuration array in my component like this.

...
config: ButtonConfig[];
...
this.config.push(new ButtonConfig(...));
...

今天,我意识到让数组表现得像字典一样有意义,因此我可以通过数字索引而不是通过名称规范地访问特定元素.我希望能够执行 config.submitButton 而不是 config [3] (即使我声明了将 submitButton 映射到请求的索引).

Today, I realized that it makes more sense to have the array behave like a dictionary so I can access the particular elements not by a numeric index but rather canonically by a name. I want to be able to do config.submitButton and not config[3] (even if I have an enum declared that maps submitButton to the requested index).

...
config = { };
...
this.config.submitButton = new ButtonConfig(...);
...

这可行,但是我现在允许一堆 any 欺骗我的代码库,这很糟糕.我希望对象知道只有 ButtonConfig 类型的东西才能放入其中.

This works but I'm now allowing a bunch of any's to spoof my code base, which is bad. I want the object to be aware that only things of type ButtonConfig can be put into it.

我可以用这些字段声明一个类,因为我希望将来可以动态添加这些字段的数量,所以下面的代码就不行了.

I can declare a class with the fields because I want the number of them to be dynamically addable in the future, so the following won't do.

export class ButtonConfigs {
  submitConfig: ButtonConfig, ...
}

我已经检查了文档一些示例并没有真正认识我在寻找什么.完全有可能还是我感到困惑?

I've check the docs and some examples not really recognizing what I'm looking for. Is it possible at all or an I confusing myself?

推荐答案

最简单的答案是这样:

export type ButtonConfigs = {
  [key: string]: ButtonConfig;
}

如果您想要高水平的动态效果,那么效果很好.

This works very well, if you want a high level of dynamics.

如果您想将其锁定一点,可以定义一个枚举,其中包含要允许的可能的键:

If you want to lock it down a little, you could define an enum that contains the possible keys you want to allow:

export enum ButtonConfigKeys {
  'submitConfig',
  'someOtherKey',
  '...'
}

export type ButtonConfigs = {
  [key: ButtonConfigKeys]: ButtonConfig;
}

这篇关于如何使用TypeScript声明属性为字符串类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆