Reputation: 21658
I was practicing with Generics classes and I found this, maybe it's normal behavior, if it is a normal behavior that what happens to public testT : T;
class Punto<T> extends Base{
..//
public testT : T;
constructor(test: string){
super();
..//
}
}
..//
let punto: Punto; <- this does not work (I expected that)
Generic type 'Punto' requires 1 type argument(s). class Punto
let punto: Punto<number>; <- this I work (I expected that)
let puntoI = new Punto('test'); <- why this works, what happens to public testT : T;
let puntoI = new Punto<number>('test'); <- this I work (I expected that)
excuse my English and I hope you now understand better, after doing a few tests, I saw some differences.
class Base{
constructor(private id: string){
}
print(){
console.log(this.id);
}
}
class DSimple<T> extends Base{
constructor(public varT: T,id: string){
super(id);
}
}
let oBase: Base = new Base('oBase');
let uSimple: DSimple = new DSimple(oBase,'der'); //<-- Now no work (I expected that)
Generic type 'DSimple<T>' requires 1 type argument(s).
class DSimple<T>
let unoSimple: DSimple<Base> = new DSimple(oBase,'derivada1'); //<-- work (I expected that)
In my other .ts
file for test to which I referred to earlier
class Base{
}
class Punto extends Base{
constructor(test: string){
super();
}
}
class Punto3<T extends Base>{
constructor(public gene: T, test: string){
}
}
..//
let puntoInicializado = new Punto('test');
let punto3 = new Punto3(puntoInicializado,'test punto 3'); <-- this work
Maybe it's because infers types yeah
because it behaves differently when using
let punto3 = new Punto3(puntoInicializado,'test punto 3'); <-- this work
let uSimple: DSimple = new DSimple(oBase,'der'); //<-- Now no work (I expected that)
let punto3 =..
--- worklet uSimple: DSimple =..
--- no worklet uSimple: DSimple<Base> =..
--- workYou have any explanation? Why the point one inferred and the point two not, and must be used for this case point three."Maybe it's a terrible question sorry if it is."
Upvotes: 0
Views: 168
Reputation: 22322
I believe your question is related to so called 'Type Argument Inference' and well covered in the following section of the typescript specification: link
[EDIT]
let punto
- works due to type inference.let uSimple: DSimple
- does not work as it violates typescript specification for type references, as explicitly stated here: type argument listslet uSimple: DSimple<Base>
- works as it has correct type reference to generic type (for more info see link above and also type references) Upvotes: 1
Reputation: 11
In the first line (let punto: Punto;
), you declare a variable's signature, so compiler makes you to specify correct type, otherwise it's a compilation error.
In the third line (let puntoI = new Punto('test');
), you just assign a value to the variable, so compiler tries to determine variable's type, but if it fails, the type defaults to any
. I can assume that puntoI
is either any
or Punto<any>
, don't know for sure.
Upvotes: 0