I have a function f<T extends 1|2>(): void
of which I am trying to specify the behavior based on T. I have tried making an if-statement if(T extends 1)...
however I get the error 'T' only refers to a type, but is being used as a value here. Which makes sense, but I'm not sure how to work around this? I can of course introduce an argument to f that is of type T, but that seems redundant. Is there an easy way to specialize parts of my function with an if statement? Or should I pass T as an argument for that instead of a type?
Asked
Active
Viewed 1,623 times
1

DottyPhone
- 320
- 1
- 12
-
1How would you do it in javascript? I'm guessing you'd need to pass an argument in and check the thing that was passed in. If so, you'll have to do the same thing in typescript. – Nicholas Tower Nov 21 '21 at 22:15
-
I suppose I was hoping TS would have some kind of transpile-time mechanism – DottyPhone Nov 21 '21 at 22:25
-
An argument to your function will have the type `T`. So to find out what `T` is, you'll need to check the type of that argument. To do that at run-time, which will be necessary here, you'll have to do it pretty much the same way as you would in plain old JavaScript, e.g. `if (myArg === 1)` – Mark Hanna Nov 21 '21 at 22:36
-
TypeScript's type system is [erased](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html#erased-structural-types), not reified like in Java. There is absolutely nothing about `T` at runtime to grab onto. Hoping for a transpile-time mechanism is unfortunately futile, as it violates [TypeScript Design Non-Goal #5](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals). The "right" way to proceed here is to imagine you were writing pure JS, come up with an algorithm that does what you want there, and then give it strong types for TS. – jcalz Nov 22 '21 at 01:08