#Constructor overloading on generic classes

4 messages · Page 1 of 1 (latest)

fallow ridge
#

I now have a generic class Graph<T> ,

class Graph<T>{
  protected _primaryKey?:string 
  protected _isDirected:boolean
  constructor(isDirected=false,primaryKey?:string){
    this._isDirected=isDirected
    this._primaryKey=primaryKey
  }
  addVertex(v:T):this{
    // todo
    return this
  }
}

// here are some examples
new Graph<string>() // ok
new Graph<number>() // ok
new Graph<{a:number}>() // type error:primaryKey is required

now I want it to pass primaryKey when T is of object type, but not when T is of other types. What do I do?

fast creek
#

but that would mean your field is not initialized in some cases @fallow ridge

#

also, your code snippet has a few errors (Class instead of class, the addVertex method not having the right syntax, etc.)

fallow ridge