在我的应用程序中,我总是遇到一些问题,即使用预先定义的一些密钥并且根本不会改变 - 即它们是硬编码的。我并不知道哪个选项最好。
目前我有:
export class PermissionKeys {
public static readonly MYKEY_NOT_ALL_SPECIFIED = 'MYKEY_NOT_ALL_SPECIFIED';
}
以及
export enum MyKey {
MYKEY_NOT_ALL_SPECIFIED = <any>'MYKEY_NOT_ALL_SPECIFIED',
}
在最终的代码中,我想比较this.checkKey=MYKEY_NOT_ALL_SPECIFIED
之类的内容。使用enum
我需要始终追加.toString()
。使用readonly
字符串,我需要指定名称和内容(始终保持完全相同)。
任何人都有更好的想法来管理硬编码密钥?
答案 0 :(得分:2)
如果没有关于您的用例的更多信息,我不确定您最好的方式是什么。您可以使用字符串枚举:
export enum MyKey {
MYKEY_NOT_ALL_SPECIFIED = 'MYKEY_NOT_ALL_SPECIFIED', // no <any>
OTHERKEY = 'OTHERKEY',
ETC = 'ETC'
}
class Something {
checkKey: MyKey;
someMethod() {
if (this.checkKey === MyKey.MYKEY_NOT_ALL_SPECIFIED) {
// do something
}
}
}
或者,如果你不想重复自己并且知道值和键总是相等的,你可以只使用一个常量的普通对象:
function sameValuesAsKeys<K extends string>(...values: K[]): {readonly [P in K]: P} {
const ret = {} as {[P in K]: P}
values.forEach(k => ret[k] = k);
return ret;
}
export const MyKey = sameValuesAsKeys('MYKEY_NOT_ALL_SPECIFIED', "OTHERKEY", "ETC");
type MyKey = keyof typeof MyKey;
// still works
class Something {
checkKey: MyKey;
someMethod() {
if (this.checkKey === MyKey.MYKEY_NOT_ALL_SPECIFIED) {
// do something
}
}
}
这会回答你的问题吗?如果没有,请更具体地说明您的用例...显示一些您无法获得所需密码的代码或您认为自己重复的地方,我会更新答案。
希望有所帮助;祝你好运!
解释
的签名function sameValuesAsKeys<K extends string>(...values: K[]): {readonly [P in K]: P}
类型参数K
是一些字符串或字符串联合,参数values
是该类型字符串的数组。如果我致电sameValuesAsKeys("dog","cat")
,TypeScript会将K
推断为"dog"|"cat"
。 sameValuesAsKeys()
的返回类型是{readonly [P in K]: P}
,它是mapped type,大致意思是“每个属性都是只读的对象,其值与键相同”。因此,如果我致电sameValuesAsKeys("dog","cat")
,则返回值的类型为{readonly dog: "dog"; readonly cat: "cat"}
。
答案 1 :(得分:0)
工作演示https://es6console.com/j7ajnnma/。请按照步骤查看结果:
enum Direction {
Up,
Down,
Left,
Right
}
/* Trues */
var value: any = 'Right';
console.log(`'Direction[value] === Direction.Right' => ${Direction[value] === Direction.Right}`);
value = 3;
console.log(`'value === Direction.Right' => ${value === Direction.Right}`);
/* False */
value = 'Up';
console.log(`'Direction[value] === Direction.Right' => ${Direction[value] === Direction.Right}`);
value = 1;
console.log(`'value === Direction.Right' => ${value === Direction.Right}`);