You cannot eliminate the type
string, but you can make your function a lot more intelligent and usable in regards to types by adding overloads:
function evaluate(variable: any, type: 'string'): string;
function evaluate(variable: any, type: 'number'): number;
function evaluate(variable: any, type: 'boolean'): boolean;
function evaluate(variable: any, type: string): unknown {
...
default: throw Error('unknown type');
}
const myBool = evaluate('TRUE', 'boolean'); // myBool: boolean
const myNumber = evaluate('91823', 'number'); // myBool: boolean
evaluate('91823', 'qwejrk' as any); // RUNTIME ERROR (violated types)
const mysteryType = 'number' as 'boolean' | 'number';
const myMystery = evaluate('91823', mysteryType); // COMPILER ERROR, no overload matches.
Playground Link
Note that there is no longer a null case, since it is impossible to know if an unknown string
type might actually be containing a valid value like 'number'
at compile-time.
This will be good enough for most people.
However...
Note above that the mysteryType union does not work. If you really really really want that to work for some reason, you can use conditional types instead:
function evaluate<T extends string>(variable: any, type: T):
T extends 'string' ? string :
T extends 'number' ? number :
T extends 'boolean' ? boolean :
never;
function evaluate(variable: any, type: string): unknown {
...
default: throw Error('unknown type');
}
const mysteryType = 'number' as 'boolean' | 'number';
const myMystery = evaluate('91823', mysteryType); // myMystery: number | boolean
Playground Link
Aditionally, if you Googled this question and are wondering how to get T
from MyClass<T>
, that is possible as well:
class MyClass<T> {}
type GetMyClassT<C extends MyClass<any>> = C extends MyClass<infer T> ? T : unknown;
const myInstance = new MyClass<"hello">();
let x: GetMyClassT<typeof myInstance>; // x: "hello"
Playground Link