【问题标题】:Typescript equivalent of decltype in C++?Typescript相当于C ++中的decltype?
【发布时间】:2020-11-21 07:14:21
【问题描述】:

C++ 中的decltype 返回表达式的类型,例如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());

【问题讨论】:

  • 在类型位置最接近的是typeof,但它仅适用于变量,不适用于表达式。见github.com/Microsoft/TypeScript/issues/6606
  • 我已经问过similar question(在找到你之前),看起来运气不好:(
  • 我在谷歌上搜索“typescript 计算接口”、“typecript 推断返回类型接口”等,但没有成功,直到我记得 c++ 等价物。 [也许这条评论对 SEO 有帮助?]

标签: typescript


【解决方案1】:

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

*/

【讨论】:

猜你喜欢
  • 2016-04-12
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 2022-12-09
  • 2011-01-24
  • 2012-09-30
相关资源
最近更新 更多