下面的代码的作用是什么?

问题描述 投票:0回答:2
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)

我可以理解在vanillaJS中检查newName是否正确,但是在Typescript中,它的目的是什么? Typescript已经保证newName是字符串,并且具有。length属性。

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

typescript accessor notnull
2个回答
1
投票

假设所有代码都是打字稿,并且是由打字稿编译的,并且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.

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

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


-1
投票

不能仅使用

newName > fullNameMaxLength

因为newName可以是未定义/为空,在这种情况下,您将得到未处理的错误。

Uncaught TypeError: Cannot read property 'length' of undefined

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

© www.soinside.com 2019 - 2024. All rights reserved.