Search code examples
typescriptmongodbmongoose

No compile time error for Typescript type mismatch


I have a function defined like this:

export async function removeUser(deleteUserId: Types.ObjectId)

When I mistakenly called this function and pass a Mongoose object's id parameter, which is a string, it triggered a runtime exception further in the code when I tried to use the .equals() method which exists on an ObjectId but not on a string:

await removeUser(deleteUser.id);

When I corrected this by passing the ObjectId, everything worked fine:

await removeUser(deleteUser._id);

My question is, why didn't I get a compile time error from Typescript if the argument is specified as an ObjectId, but a string is being passed?

Edit: I see that the .id is defined as any, not as a string. I suspect that will factor into the answer?


Solution

  • I see that the .id is defined as any, not as a string.

    Values of type any allow assignment to any type.

    const n: number =  'string' as any // fine
    

    It's an escape hatch from the type system. So any is not typesafe and should be avoided at all costs.

    See Documentation:

    The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.