下面这段代码的目的是什么?

What is the purpose of this code in below?

const fullNameMaxLength = 10;

class Employee {
private _fullName: string;

set fullName(newName: string) {
    if (newName && newName.length > fullNameMaxLength) {
        throw new Error("fullName has a max length of " + fullNameMaxLength);
    }

    this._fullName = newName;
}
}

if (newName && newName.length > fullNameMaxLength)

我可以理解检查 newName 在 vanillaJS 中是否真实,但是在 Typescript 中,这样做的目的是什么?打字稿已经保证 newName 是字符串并且它有 .length 属性.

完整代码在这里: https://www.typescriptlang.org/docs/handbook/classes.html

你不能只使用

newName > fullNameMaxLength

因为 newName 可以是 undefined/null,在这种情况下,您将收到未处理的错误。

Uncaught TypeError: Cannot read property 'length' of undefined

接下来,您需要检查 newName.length 并与 fullNameMaxLength 进行比较。

假设所有代码都是打字稿,并且是打字稿编译的,并且没有涉及的值是any,那么这个存在性检查没有任何意义。

然而,正如其他评论者指出的那样,如果任何代码是普通的 javascript,或者作为库公开用于未知代码库或环境,则无法保证类型安全。因此,由开发人员决定是否进行双重检查。

但是,这里有一些方法,以这种方式编写它可能仍然是好的:

  1. 非打字稿调用者
// foo.js
employee.fullName = null // not typescript so no error.
  1. 可能会传入 any 类型
// foo.ts
const jsonData: any = { employees: [{ fullName: null }] } // data from a remote api

// no error because `any` be cast to any other type without error.
employee.fullName = jsonData.employees[0].fullName is any.

存在性检查可以防止这两种情况引发的错误。但是,下一行无论如何都会分配错误的值...

我认为,作为打字稿文档中的示例,存在性检查可能不应该存在,因为它有点令人困惑。