代码之家  ›  专栏  ›  技术社区  ›  Renari

如何在定义文件中声明对象枚举?

  •  0
  • Renari  · 技术社区  · 8 年前

    给定以下javascript文件(test.js):

    const someType = {
      val1: "myvalue",
      val2: "myothervalue"
    };
    
    function sampleFunction(param) {
      return 1;
    }
    
    function sampleFunction2(param) {
      return 2;
    }
    
    export {someType, sampleFunction, sampleFunction2};
    

    以及以下定义文件(test.d.ts):

    declare module "test" {
      // basically an enum object in the module
      export type someType = {
        val1: 'myvalue',
        val2: 'myothervalue',
      }
    
      export function sampleFunction(param1: someType): number;
      export function sampleFUnction2(param1: someType): number;
    }
    

    在定义文件中定义对象枚举的正确方法是什么?

    import sampleFunction, someType from 'test';
    
    console.log(sampleFunction(someType.val1)); /// someType is unavailable
    

    上面的内容不起作用,因为似乎sometype不是有效值。导入时使用 { someType } 给出一个单独的错误,它是一个用作值的类型。

    https://codepen.io/Renari/project/editor/DQNjeO#0

    1 回复  |  直到 8 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    8 年前

    类型不能出现在表达式中。您希望用此类型声明常量,因为该常量已声明并且将在运行时存在:

    declare module "test" {
      export const someType: {
        val1: 'myvalue',
        val2: 'myothervalue',
      }
      type someTypeValue = typeof someType[keyof typeof someType];
      export function sampleFunction(param1: someTypeValue): number;
      export function sampleFUnction2(param1: someTypeValue): number;
    }
    // usage.ts
    import { sampleFunction, someType} from 'test';
    
    console.log(sampleFunction(someType.val1));
    console.log(sampleFunction('myvalue')); // will also work
    

    上面的示例直接公开const,并允许您传入任何值为 sampleType

    还可以使用实际枚举对此进行建模,该枚举将隐藏常量中的字符串值:

    declare module "test" {
      export enum someType {
        val1 = "myvalue",
        val2 = 'myothervalue'
      }
      export function sampleFunction(param1: someType): number;
      export function sampleFUnction2(param1: someType): number;
    }
    // usage.ts
    import { sampleFunction, someType} from 'test';
    
    console.log(sampleFunction(someType.val1));
    console.log(sampleFunction('myvalue')); // error
    

    取决于您想要实现什么,任何一个版本都可以工作

    推荐文章