管理静态密钥的最佳方法是什么? (TS)

时间:2017-09-07 13:51:28

标签: typescript

在我的应用程序中,我总是遇到一些问题,即使用预先定义的一些密钥并且根本不会改变 - 即它们是硬编码的。我并不知道哪个选项最好。

目前我有:

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字符串,我需要指定名称和内容(始终保持完全相同)。

任何人都有更好的想法来管理硬编码密钥?

2 个答案:

答案 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
    } 
  }
}

这会回答你的问题吗?如果没有,请更具体地说明您的用例...显示一些您无法获得所需密码的代码或您认为自己重复的地方,我会更新答案。

希望有所帮助;祝你好运!

更新1

解释

的签名
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/。请按照步骤查看结果:

  1. 打开你的掌管台
  2. 选择compiler =&gt; “打字稿”
  3. 点击“转化”
  4. 点击“运行”
  5. 演示代码:

    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}`);