打字稿中方法返回类型为 null

Mar*_*rek 4 null types object typescript angular

我的问题很简短,我会举一个例子。我有一些课:

class A {
  public property: Property;

  constructor(data: any) {
    this.property = this.parseProperty(data)
  }

  private parseProperty(): Property {
    return data.property
      ? {
          name: data.property.name,
          code: data.property.code,
        }
      : null;
  }
}
Run Code Online (Sandbox Code Playgroud)

鉴于上面的例子,我应该添加'| null' 到 parseProperty 方法的返回类型?这样做有什么寓意吗?另外,我应该添加| 属性声明为空?没有它它工作得很好。

JB *_*zet 7

这取决于。

如果您将 TypeScript 项目配置为使用严格的 null 检查,则 Poperty 类型的值可能不为 null。因此,只有当您使用时,您的代码才会编译

public property: Property | null;
Run Code Online (Sandbox Code Playgroud)

private parseProperty(): Property | null {
Run Code Online (Sandbox Code Playgroud)

如果您没有,那么这基本上是一个关于代码的可读性和冗长性的选择问题。您可以选择更详细,但可以通过使用更清楚地了解变量的内容

public property: Property | null;
Run Code Online (Sandbox Code Playgroud)

通过阅读该代码,您或您的同事将记住该值可能为空,并且需要考虑这种情况。

或者您可以认为这是隐式的或过于冗长,并保持原样。

有时,很明显值可能为空。有时,很明显它们不可能为空。有时,它根本不明显,即使不激活严格的空检查,使其明确也会有所帮助。