Is it possible in TypeScript to implement a generic function that automatically converts a string value to a primitive type specified as the generic function's type argument?
Basically I would like to do something like this:
const v1: boolean = getValue<boolean>("false"); // returns false
const v2: number = getValue<number>("2345"); // returns 2345
const v3: string = getValue<string>("2345"); // returns "2345"
const v4: number = getValue<number>("false"); // throws an error
Instead, since Typescript erases types at compile time, you should instead specify the type as a parameter. I will leave the JS implementation up to you, and more specifically focus on getting the return type correctly.
Notably, you can't get an inferenced return value, specifically like
falseor"2345", this is just a limitation of how we infer the values.View this on TS Playground