typescript - 枚举中的 <any> 以及 typescript 中的字符串

标签 typescript

我已经完成了以下片段来支持带有字符串的枚举

enum Color {
    red = <any>"red", green = <any>"green", Blue = <any>"blue"
}

有什么方法以及为什么我们需要它?

最佳答案

What is the means

Typescript 枚举只是数字。因此,如果你分配一个字符串,编译器会提示。

enum Color {
    red = "red" // error `string` is not assignable to color
}

但是通过使用any,您是在告诉编译器嘘……我更清楚More on this

注意:如果您这样做,您可能需要再次 shhhhh 编译器,例如:

enum Color {
    red = <any>"red" // shhhh
}

var foo = Color.red; // okay
foo = 123; // okay: TypeScript still thinks red is a number  
foo = "red"; // Error
foo = <any>"red"; // shhhhh

断言到底是什么

enter image description here

基于替代字符串的枚举

why we need it

如果您想要基于字符串的枚举。我个人现在使用这种模式:https://basarat.gitbooks.io/typescript/content/docs/tips/stringEnums.html

Typescript 1.8 将会提供一流的支持,例如

type Foo = "a" | "b"; 

关于typescript - 枚举中的 <any> 以及 typescript 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684133/

相关文章:

typescript - Express-validator 验证导致 typescript 错误 : request. query Object is possibly 'undefined'

javascript - “React” 未定义 React Router with Typescript

typescript - Visual Studio 2015 RC 在保存 Typescript 文件时不创建 sourcemap

reactjs - 类型 'IntrinsicAttributes & { children?: ReactNode; }' 上不存在属性

angularjs - couchdb angularJS http服务回调错误响应没有有用信息

angular - 如何使用 ngForTemplate 包装模板?

typescript - 如何修复错误 TS1015 : Parameter cannot have question mark and initializer?

创建泛型方法的 Angular 最佳实践

typescript - 通过 bazel 执行 Jasmine 测试时未找到规范

javascript - 使用 componentDidUpdate 更改组件中的状态