[英]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?无论如何,是否可以创建一个函数,该函数返回 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.我可以让 modClass 函数返回类型 any 并且
typeof
是正确的。 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. typeof
是在表达式中使用时的 Javascript 运算符,它将按照预期返回类的object
。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.