【问题标题】:Type comparison: 'QuestionType' only refers to a type, but is being used as a value here类型比较:'QuestionType' 仅指一种类型,但在这里用作值
【发布时间】:2017-11-30 10:25:23
【问题描述】:

由于某种原因,我无法比较类型。我有以下域类:

export type QuestionType = 'TextOnly'
  | 'RadioListQuestion'
  | 'DropDownListQuestion'
  | 'CheckBoxQuestion'
  | 'NumberQuestion'
  | 'DateQuestion'
  | 'TextQuestion'
  | 'QuestionGroup';

在我的组件中,我想与这样的类型进行比较:

if(question.type == QuestionType.QuestionGroup.) {
   // some logic here
}

但它会引发编译错误:

'QuestionType' only refers to a type, but is being used as a value here.

谁能指出正确的解决方案?

@Update 正如@betadeveloper 建议的那样,我在方法定义中添加了类型检查,不幸的是它不起作用:

formGroupStructure = questionGroup.questions.reduce((accumulator, question: { type: QuestionType }) => {

        // If it's a nested question group (QuestionGroup inside questions[])
        if(question.type === 'QuestionGroup') {

          const formGroupStructure = this.createQuestionGroupFormGroupStructure(question.questionGroup);

          const segmentControl: AbstractControl = formGroup.get(tab.id)['controls'][segment.id];
          (<FormGroup>segmentControl).addControl(segment.questionGroup.id, this.formBuilder.group(formGroupStructure));
        } else {

          // treat normal questions: Add them to the accumulator
          if (isQuestionAnswerable(question)) {
            accumulator[question.id] = [
              question.selection,
              question.isMandatory ? [Validators.required] : [],
            ];
          }

        }

        return accumulator;
  }, {});

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    只需导入并使用确切的类型。在您的示例中,您可以这样做:

    if(question.type == QuestionGroup) {
       // some logic here
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 2019-10-08
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2018-12-30
      • 2019-09-16
      • 2017-08-16
      相关资源
      最近更新 更多