简体   繁体   English

将 null 分配给类型化变量时,Visual Studio Code 在 Typescript 代码中报告错误

[英]Visual Studio Code reports error in Typescript code when null is assigned to a typed variable

I have the following interface:我有以下界面:

interface CompositeNodeInterface {
  name: string;
  definer: any;
  parent: CompositeNodeInterface;
  children: [CompositeNodeInterface];

  addChild(definer: any): CompositeNodeInterface
}

As you can see, attribute parent is typed as an object that recursively implements the same interface, and attribute children is typed as an array of objects that equally implement recursively the same interface.如您所见,属性parent的类型是 object,它递归地实现相同的接口,属性children项的类型是一个对象数组,它们同样递归地实现相同的接口。

I have the following class that implements CompositeNodeInterface :我有以下实现CompositeNodeInterface的 class :

export default class CompositeNode implements CompositeNodeInterface {
  name: string;
  definer: any;
  parent: CompositeNode;
  children: [CompositeNode];

  constructor(definer: any) {
    switch(definer.constructor.name) {
      case 'Object':
        if ('name' in definer) {
          this.name = definer.name;
        } else {
          this.name = String(Object.values(definer)[0]);
        }

        break;
      default:
        this.name = definer.toString();
    }

    this.definer = definer;
    this.parent = null;
    this.children = [];
  }

  acceptVisit(visitor: VisitorInterface) {
    return visitor.visit(this)
  }
}

The problem is that when attribute parent is set to null , VSC reports the following error: Type 'null' is not assignable to type 'CompositeNode' , and when attribute children is set to [] , VSC reports Type '[]' is not assignable to type '[CompositeNode]' .问题是当属性parent设置为null时,VSC 报告以下错误: Type 'null' is not assignable to type 'CompositeNode' ,并且当属性children设置为[]时,VSC 报告Type '[]' is not assignable to type '[CompositeNode]'

在此处输入图像描述

I read here that all attributes are nullable, so I would expect these operations to be valid.在这里读到所有属性都是可以为空的,所以我希望这些操作是有效的。

you no longer can assign null or undefined values to every field since: https://github.com/Microsoft/TypeScript/pull/7140您不再可以为每个字段分配 null 或未定义的值,因为: https://github.com/Microsoft/TypeScript/pull/7140

you need to explicitly set the value to nullable, possibly using of a union type, such as CompositeNode | null您需要将值显式设置为可为空,可能使用联合类型,例如CompositeNode | null CompositeNode | null , or additionally you could make parent optional CompositeNode | null ,或者另外你可以让父母可选

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM