Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript equivalent of decltype in C++?

Tags:

typescript

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());
like image 888
Amin Roosta Avatar asked Aug 16 '17 01:08

Amin Roosta


1 Answers

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;
    }

*/
like image 117
Clint Avatar answered Sep 20 '22 21:09

Clint