简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM