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

时间:2018-08-07 17:52:43

标签: typescript

给出以下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 个答案:

答案 0 :(得分:1)

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

 class  Navbar extends React.Component {
 render(){
    return (
        <Nav bsStyle="tabs"> 
            <LinkContainer to="/login" >
                <NavItem >
                        LogIn
                </NavItem>
            </LinkContainer>
            <LinkContainer to="/Register" >
                <NavItem >
                    Register
                </NavItem>  
            </LinkContainer>
            <Router>
                <BrowserRouter>
                    <Switch>
                        <Route path="/Register" component={Register}  />
                        <Route path="/Login" component={Login}  />
                    </Switch>
                </BrowserRouter>
            </Router>
        </Nav> 
    ) 
}}                                         

以上示例直接暴露了const,并允许您传递值为<a href='URL GOES HERE'><img src="link-to-photo"></a>的任何字符串。

您还可以使用实际的枚举对此建模,这将在const中隐藏字符串值:

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

取决于您要实现的任一版本的作用