[英]JSDoc: how to define a type that's equal to object's property names- like Typescript's keyof?
[英]Is it possible to define a type for property names in 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
]
}
然后我有SettingsService
在getItemsFromStorage()
方法中使用这些常量。 基本上,它的作用是循环遍历SettingsConstants
定义的字符串,并将其自己的properties
设置为等于从storage
获取的value
,否则设置默认value
。
SettingsService.ts
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
property
,而不是本意。
我想要的解决方案
我想定义一个类型,在其中我可以定义允许使用的变量的名称。 与此类似
export declare namespace SettingsTypes{
type SettingsType = "settingsAllowed" | "quitAllowed";
}
然后在SettingsService
我可以写以下内容
private settingsAllowed: SettingsTypes.SettingType: boolean;
因此其类似的settingsAllowed
名称必须为SettingsTypes.SettingType
类型,其返回类型为boolean
但是,这似乎没有多大意义,而且似乎没有办法正确地做到这一点,所以我想知道你们中的任何一个聪明的头脑是否可能对这个问题有很好的解决方案。
这是一个有趣的问题。 我去看了一些文档。 请特别查看类型防护的部分。 也许您可以在为布尔型做类型保护的地方做类似的事情?
function isSetting(setting: any): setting is Settings {
return typeof setting === SettingsTypes.SettingType;
}
与此类似。 这只是一个可能的想法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.