How can I return the same type as I pass into a function in Typescript?

2071 views typescript
2

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.

answered question

1 Answer

10

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)

protected modClass<T>(modMe: T): T {
    console.log(modMe);
    return modMe;
}
const modded = modClass(new SomeClass()); // nodded is SomeClass

posted this

Have an answer?

JD

Please login first before posting an answer.