4 ms·
type MyPolymorphicType = { type: 'A', value: number } | { type: 'B', value: string } There you have types at runtime. If you really want to be pedantic about i
by DanielHB 3y ago
type MyPolymorphicType = { type: 'A', value: number } | { type: 'B', value: string }
There you have types at runtime. If you really want to be pedantic about it you can use classes and instanceof as well
In fact even Java removes types at runtime for code that uses generics, so often you need to do something like that as well
Types as a static analysis tool is great, types tied to the underlying hardware and memory structures have their values (usually performance benefits). Conflating both together usually leaves you with a very weak (unsafe) type system.
- Draiken 3y agoThat's using values to determine different types. What I'm talking about is true type validation where I can detect differences between the same data. TypeA = number TypeB = number const myNumber = someFunctionThatReturnsTypeAorB() I cannot tell which number I'm dealing with because TS doesn't know that type at runtime. I don't think this is about being pedantic. If the language forces you to change the data structure to allow you to differentiate types at runtime, then it's a very limited type system IMO. If all of this came for free, I wouldn't argue with it. But people tend to disregard all of the cost that comes with it. I know I have lost countless hours simply changing code that already works to make TypeScript happy. If all that is to tell me I shouldn't use a string in a number argument, I don't know if the benefits outweigh the cost.