3 ms·
TypeScript checks that the types are correct at compile time. If you are strict, don’t intentionally try to outsmart the type system, and use manual runtime ty
by __ryan__ 6y ago
TypeScript checks that the types are correct at compile time.
If you are strict, don’t intentionally try to outsmart the type system, and use manual runtime type checking when necessary [0], TypeScript does a good practical job of ensuring that you won’t run into runtime type errors.
The reason TypeScript doesn’t automatically include runtime type information is (probably) because the overhead of runtime type checking would outweigh the benefit when static type checking does a good enough job.
Also, JavaScript being a dynamic language has allowed some pretty complex patterns of types to emerge from real-world use cases that would be exhausting to enforce all the time at runtime. Typically in TypeScript, runtime type checking is (manually) done when the type system cannot otherwise confidently guarantee the type of a value. For example, it’s common to have a runtime check for the shape of a JSON api response because you’re not necessarily in control of what that will actually return. There are community supported packages to help make this easier [1].
0: https://www.typescriptlang.org/docs/handbook/advanced-types.html https://www.typescriptlang.org/docs/handbook/advanced-types....
1: https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts