在JS中,我的很多模块都只是包装静态函数,枚举和属性的对象。例如,我有一个类似于此的模块Debug
(我真的简化了它):
export default Debug = {
// Current mode set, enum value from Modes. Setted outside of the module (see below).
mode : null,
// Enum of all possible modes
Modes : {
DEV : 0,
PROD : 1,
},
// getter, checks if it's in production mode
get isInProdMode() {
return Debug.mode === Debug.Modes.PROD;
},
// If the condition is met, it will throw an error in development mode, or just silently log a warning in production mode
assert : function(condition, message){
if (condiftion) {
if (Debug.isInProdMode)
console.warn(message);
else
throw message;
}
}
}
// index.js
Debug.mode = Debug.Modes.DEV;
如何在Typescript中创建这样的匿名对象?以Enum作为财产?还有吸气功能?所有属性都是已知的。 我真的卡住了。
答案 0 :(得分:4)
我倾向于解决这些问题的方法是只为匿名对象的属性创建接口,然后为匿名对象创建接口:
@media screen and (max-width: 340px){
#mig-header > a {
max-width: 200px;
}
#mig-header > button {
padding: 0.25rem;
}
}
答案 1 :(得分:1)
我会说惯用的方法是使用命名空间。
SPARK_MAJOR_VERSION is set to 2, using Spark2
Python 2.7.12 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:42:40)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel).
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 2.0.2.2.5.6.2-9
/_/
Using Python version 2.7.12 (default, Jul 2 2016 17:42:40)
SparkSession available as 'spark'.
>>> import tensorflow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named tensorflow
但是,命名空间不支持getter和setter,因此需要将getter转换为常规函数。
如果需要将此代码声明为对象,则可以先定义枚举,然后从对象中引用。
namespace Debug {
export enum Modes { DEV, PROD }
export var mode: Modes = Modes.DEV;
export function isInProdMode(): boolean {
return mode === Modes.PROD;
}
export function assert(condition: boolean, message: string) {
if (condition) {
if (isInProdMode()) {
console.warn(message);
} else {
throw message;
}
}
}
}
export default Debug
答案 2 :(得分:0)
// index.js
import Debug from './debug';
Debug.mode = Debug.Modes.DEV;
console.log(Debug.isInProdMode);
// false