decltype
in C++ returns the type of an expression, for example decltype(1+1)
will be int
.
Note that the expression won't be executed or compiled.
Does Typescript has something similar?
Example usecase that i think should work:
const foo = () => ({a: '', b: 0});
type foo_return_type = decltype(foo());
// foo_return_type should be '{a: stirng, b: number}`
import { bar } from './some_module';
type my_type = decltype(new bar().some_method());
You can use ReturnType
for this (introduced in typescript 2.8)
function foo() {
return {a: '', b: 0}
}
class bar {
some_method() {
return {x: '', z: 0}
}
}
type fooReturnType = ReturnType<typeof foo>
/**
type fooReturnType = {
a: string;
b: number;
}
*/
type barReturnType = ReturnType<typeof bar.prototype.some_method>
/**
type barReturnType = {
x: string;
z: number;
}
*/
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