简体   繁体   中英

Tests don't run because typescript throws error when trying to test type checking

Trying to test to make sure that a typed variable can only be assigned certain values. Is there a way to use jest to throw an error if an invalid value is assigned, without typescript preventing the tests from running and throwing an error before tests run?

In class constructor:
defaultValue: string | null

In test:
expect(() => instance.defaultValue = 100).toThrow()

I expect that the test should run and acknowledge that this does throw an error, but the error is thrown before the test runs, preventing all tests from running.

Typescript is not a runtime type checker, it is a compile time type checker. This means that all types are checked before the code is converted to javascript and if there is a type error the compile fails. If your class takes data from an unverified source, IE an API you cannot check that with typescript.

Your test implies 1 of 2 things:

Either Your constructor is meant to consume data that is only known at runtime, but should always be a string and must throw an error if it is not. In that case you may cast your class to any this removes type checking completely for this object, but it will allow you test that your class throws an error.

const instance = new (MyClass as any)(42) // throws an error

Or your class is only used by data the developer explicitly provides to it and your test only verifies that typescript will not allow a developer to make a mistake. In that case, this is not a useful test and you should probably remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM