Search code examples
typescriptaccessornotnull

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)

I can understand to check that newName is truthy or not in vanillaJS but, in Typescript what is the purpose of that? Typescript already guarantees that newName is string and it has .length property.

full code is here: https://www.typescriptlang.org/docs/handbook/classes.html


Solution

  • Assuming all code is typescript, and compiled by typescript, and no value involved is any, then this existence check serves no purpose.

    However, as other commenters point out, if any code is plain javascript, or exposed as a library to be used on unknown codebases or environments, then type safety cannot be guaranteed. So it's up to the developer to decide to do double checks.

    But, here's some ways that it might still be good to write it that way:

    1. non-typescript caller
    // foo.js
    employee.fullName = null // not typescript so no error.
    
    1. a type of any might be passed in
    // 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.
    

    The existence check would guard against an error being thrown by both of these cases. However, the very next line would assign the bad value anyway...

    I would argue that, as an example in the typescript docs, the existence check probably should not be there, as it is a bit confusing.