0

I've the following ValueObject classes to encapsulate IDs:

class UserID {
    constructor(readonly id: number) {}
}

class ProductID {
    constructor(readonly id: number) {}
}

And the following function:

function addUser(user : UserID) : Promise<void> {
   //... do stuff
}

const productID = new ProductID(1);
addUser(productID); //<-- This won't trigger any build error :(

The compiler will accept addUser(new ProductID(1)) as a correct statement. I know it's impossible to typecheck this function at runtime due JavaScript "limitations", but why we can't get an error at developement time?

I want typechecking to check function parameter types configurable via tsconfig.json.

  • In JavaScript we would write `if (user instanceof UserID) { ... }` to check it at runtime... – kelsny Dec 01 '22 at 17:23
  • I think you want to use `InstanceType` over just using `UserID` which is a class, as a type. Also, be sure to turn on strict mode in tsconfig.json – mykeels Dec 01 '22 at 21:19

0 Answers0