代码之家  ›  专栏  ›  技术社区  ›  Tim Cooper

在编译时从类型字段中提取常量字符串

  •  0
  • Tim Cooper  · 技术社区  · 5 年前

    我有一个类型,其字段具有常量字符串文字。我想通过名称引用我的类型和字段,以便在代码的其他地方使用这个字符串文字。例如:

    export type MyType = {
        action?: 'TestAction';
        arg0: true,
    };
    
    /////
    
    let input: any = {
        action: 'XYZ',
    };
    
    if (input.action === MyType.action) { // This obviously does not work
        // TODO: perform TestAction
    }
    

    除了搬家,还有什么方法可以做到这一点吗 'TestAction' 按照它自己的常量定义?

    0 回复  |  直到 5 年前
        1
  •  0
  •   chrismclarke    5 年前

    可以将类型声明为常量,并在两个位置引用

    const ActionType = "TestAction";
    
    export type MyType = {
      action?: typeof ActionType;
      arg0: true;
    };
    
    /////
    
    let input: any = {
      action: "XYZ",
    };
    
    if (input.action === ActionType) {
      // This obviously does not work
      // TODO: perform TestAction
    }
    

    另一个选项是使用switch语句(可选地强制类型从 MyType 打字,即。

    export type MyType = {
        action?: 'TestAction';
        arg0: true,
    };
    
    
    /////
    
    let input: any = {
        action: 'XYZ',
    };
    
    switch (input.action as MyType['action']) {
        case 'TestAction':
            // perform TestAction
            break;
    
        default:
            break;
    }
    
        2
  •  0
  •   Connor Low Porkopek    5 年前

    在运行时不能在TS land中使用任何东西,所以 const 定义可能是你最好的选择。如果你不想改变 MyType ,你可以这样做:

    // Enforce consistency with MyType's definition
    const TEST_ACTION: MyType['action'] = 'TestAction';
    

    Playground .

    推荐文章