This code snippet demonstrates a type-safe approach:
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
It is important to note that using explicit generics unrelated to any argument can lead to unsafe code:
function fn<Char extends "a">(): Char {
return "a" // error
}
const result = fn<'a' & { hello: 42 }>()
const check = result.hello // 42, but undefined in runtime
Check out my article for more information on inference.