在Angular库中创建时,instanceof返回false

问题描述

在Angular库中创建对象时,instanceof返回false。

import {
  Component,OnInit
} from '@angular/core';
import {
  FormControl,} from '@angular/forms';
import {genControl} from 'test-lib';                        // import a function from my own library.

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{

  constructor() {
  }

  ngOnInit() {

    const fcA = genControl();                               // Create a FormControl in Angular Library
    const fcB = new FormControl('');

    if (fcA instanceof FormControl) {
      console.log('fcA is instanceof FormControl');
    } else {
      console.log('fcA is not instanceof FormControl');     // displays this.
    }

    if (fcB instanceof FormControl) {
      console.log('fcB is instanceof FormControl');         // displays this.
    } else {
      console.log('fcB is not instanceof FormControl');
    }

  }
}

test-lib一个this post的Angular Library项目构建。 genControl代码如下。

import {FormControl} from '@angular/forms';

export function genControl(): FormControl {
  return new FormControl('');
}

上面的代码输出如下。

fcA is not instanceof FormControl
fcB is instanceof FormControl

为什么fcA不是FormControl的实例?我该如何解决fcAFormControl的实例?

主项目AppComponent与Angular库genControl间的Angular版本是相同的,即9.1.11。

解决方法

正如@andriishupta所述,这是因为应用程序和lib从不同的文件中导入了FormControl。 我应该在paths中指定tsconfig.json,如下所示。

  "compilerOptions": {
        :
    "paths": {
      "@angular/*": [
        "./node_modules/@angular/*"
      ]
    }
  },