是否可以在TypeScript中为属性名称定义类型

时间:2017-12-08 21:40:39

标签: javascript typescript

所以我有这个常量class,它定义了我保存到localStorage / chrome.storage的变量的名称,以及如果项目没有的话,它们的默认值是什么存在于存储中。

SettingsConstants.ts

export class SettingsConstants {
  public static SETTINGS_ALLOWED: string = "settingsAllowed";
  public static QUIT_ALLOWED: string = "quitAllowed";

  public static DEFAULTS: any = () => {
    const defaults = {};
    defaults[SettingsConstant.SETTINGS_ALLOWED] = true;
    defaults[SettingsConstant.QUIT_ALLOWED] = true;
    return defaults;
  };

  public static STORAGE_STRINGS: string[] = [
      SettingsConstant.SETTINGS_ALLOWED,
      SettingsConstant.QUIT_ALLOWED
    ]
}

然后我SettingsServicegetItemsFromStorage()方法中使用这些常量。基本上它的作用是它遍历SettingsConstants中定义的字符串,并将其自己的properties设置为等于value得到的storage,否则设置默认{ {1}}。

SettingsService.ts

value

代码有效,但它没有静态检查,这是我想要的。检查export class SettingsService implements ISettingsService { private settingsAllowed: boolean = undefined; private quitAllowed: boolean = undefined; constructor(logger: Logger) { this.logger = logger; this.getItemsFromStorage(); } private getItemsFromStorage(): void { const storageStrings: string[] = SettingsConstant.STORAGE_STRINGS; for (let i = 0; i < storageStrings.length; i++) { const currentString = storageStrings[i]; if (!this.hasOwnProperty(currentString)) { throw "The property is not defined, " + "check if it matches the STORAGE_STRING in SettingsConstants"; } const currentItem = this.getItem(currentString); this[currentString] = currentItem === undefined ? SettingsConstant.DEFAULTS()[currentString] : currentItem; this.logger.log(currentString, "=", this[currentString]); } } private getItem(item: any): any { const localItem: string = localStorage.getItem(item); if (localItem === undefined || localItem === null || localItem === 'undefined') { return undefined; } else { return JSON.parse(localItem); } } } 是否有SettingsService的当前方法是将property设置为property然后使用

undefined

要检查变量是否存在于if (!this.hasOwnProperty(currentString)) { throw "The property is not defined, " + "check if it matches the STORAGE_STRING in SettingsConstants"; } 中,如果它不存在那么它必然意味着我们可能拼写错误,或者忘记添加它。

我可以通过将它们添加到class ISettingsService来解决此问题,但这意味着interface将成为property而非意图

我想要的解决方案

我想定义一个类型,我可以在其中定义允许使用的变量的名称。与此相似

public

然后在export declare namespace SettingsTypes{ type SettingsType = "settingsAllowed" | "quitAllowed"; } 我可以写下面的

SettingsService

所以它的private settingsAllowed: SettingsTypes.SettingType: boolean; 名称必须是settingsAllowed类型,其返回类型为SettingsTypes.SettingType

然而,这似乎没有多大意义,似乎没有办法正确地做到这一点,所以我想知道你们中任何一个聪明的脑袋是否可能有一个很好的解决方案来解决这个问题。

1 个答案:

答案 0 :(得分:1)

这是一个有趣的问题。我去看了一些文档。特别要看看型号防护装置的部分。也许你可以做类似的事情,你可以为boolean做一个类型保护?

function isSetting(setting: any): setting is Settings {
return typeof  setting === SettingsTypes.SettingType;
}

类似于此的东西。这只是一个可能的想法

Advanced Types