C++中decltype的Typescript等价物?

x759pob2  于 2023-04-07  发布在  TypeScript
关注(0)|答案(2)|浏览(130)

decltype在C++中返回表达式的类型,例如decltype(1+1)将是int
请注意,不会执行或编译表达式。
Typescript有类似的功能吗?
我认为应该工作的示例用例:

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());
hkmswyz6

hkmswyz61#

您可以使用ReturnType(在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;
    }

*/
s6fujrry

s6fujrry2#

我想得到一个类型上的字段的类型,键查找对我有用Class['field']而不是Class.field
不知道为什么,但它确实!

type Foo = {
    bar: (b: number) => void;
}

type BrokenBar = Foo.bar; //doesn't work
type Bar = Foo['bar']; //does compile

此处演示

相关问题