【问题标题】:How to get generic type parameter in typescript?如何在打字稿中获取泛型类型参数?
【发布时间】:2021-10-11 17:51:16
【问题描述】:

在下面的代码中,我想获取 E 的类型。 但我找不到 E 的 get 类型。

class A<E> {
  getParameterType() {
    // I want get type of E
  }
}

class B {
}

** Example **
new A<number>().getParameterType() // number
new A<B>().getParameterType() // B

【问题讨论】:

标签: typescript typescript-generics


【解决方案1】:

这是执行此操作的类型安全方法:

class A<E> {
    constructor(public generic: E) { }
    getParameterType() {
        return this.generic
    }
}

class B {
}

const result1 = new A(42).getParameterType() // number
const result2 = new A(new B()).getParameterType() // B

请注意,使用与任何参数无关的显式泛型是不安全的:

function fn<Char extends "a">(): Char {
    return "a" // error
}

const result = fn<'a' & { hello: 42 }>()

const check = result.hello // 42,but undefined in runtime

Here,在我的文章中,您可以找到更多关于推理的信息。

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2020-12-22
    • 1970-01-01
    相关资源
    最近更新 更多