打字稿-导入后未定义导出的变量(字典)

时间:2019-06-22 17:34:37

标签: angular typescript

在.ts文件中,我定义了如下字典:

export var substatuses = {
    'not_actuated': {
        name: 'Not actuated',
        color: '#F52323',
        iconColor: 'color-red'
    },
    'executing_procedure': {
        name: 'Executing procedure',
        color: '#F78521',
        iconColor: 'color-orange'
    },
    'procedure_executed': {
        name: 'Procedure executed',
        color: '#F2C618',
        iconColor: 'color-yellow'
    },
    'unknown': {
        name: 'Unknown',
        color: '#767676',
        iconColor: 'color-gray'
    },
    'can_not_act': {
        name: 'Can not act',
        color: '#0082F0',
        iconColor: 'color-blue'
    },
    'ok': {
        name: 'Ok',
        color: '#36B07F',
        iconColor: 'color-green'
    },
};

然后在Angular组件上,通过以下方式导入它:

import { substatuses } from 'src/app/core/dictionaries/substatuses';

并尝试用作普通词典:

substatuses['ok']

但是我收到“错误TypeError:无法读取未定义的属性'ok'”。

为什么我的变量没有在组件之前初始化?

1 个答案:

答案 0 :(得分:2)

使用var声明的变量被吊起(https://developer.mozilla.org/en-US/docs/Glossary/Hoisting),这意味着何时定义它们和何时设置值可能与代码中的内容不匹配。

当今最好的方法是根本不使用var。使用ES6 constlet声明所有变量,它们将不再悬挂,因此更易于理解。

相关问题