Home > Software engineering >  How to get generic type parameter in typescript?
How to get generic type parameter in typescript?

Time:10-12

In the code below, I want to get type of E. But I can't find get type of E.

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

class B {
}

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

CodePudding user response:

This is the type safe approach to do this:

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

Please be aware that it is unsafe to use explicit generic which is not related to any argument:

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, in my article, you can find more about inference.

  • Related