I have a function which I'd like to be able to pass a class to and have it return the same type as that class.
Currently, the best way I've found is like so:
protected modClass<CLASS_TYPE>(modMe: CLASS_TYPE): CLASS_TYPE {
console.log(modMe);
return modMe;
}
const modded = modClass<SomeClass>(new SomeClass());
The above isn't awful, it does work, but it's not really returning the type of the class passed to the function so much as having it predefined and refusing to take any other class type.
What I'd like to be able to do (for example) is this:
const modded = modClass(new SomeClass());
console.log(typeof modded); // SomeClass;
Is there anyway to make a function which returns whatever the type of one of it's arguments is in TypeScript?
Edit: I should mention, I'm not just trying to have the type be correct, but be checked. I could have the modClass function return type any and typeof
would be correct. It just wouldn't have any real type checking.
typeof
is the Javascript operator when used in expressions and will return object
for classes as it is supposed to do.
As for your function, the generic parameter will be inferred correctly by the compiler you don't have to specify it explicitly. (Changed the name to conform to conventions but it should work regardless)
class SomeClass{
bar(){}
}
function modClass<T>(modMe: T): T {
console.log(modMe);
return modMe;
}
const modded = modClass(new SomeClass()) // modded is SomeClass
modded.bar()
Playground link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With