Search code examples
typescriptd3.jstypescript-generics

what means a type like SomeType<T, U, V> in typescript?


I'm using d3 with typescript and there is a lot of types in d3 that are like this SomeType<U,T,V>. Example:

merge(other: Selection<GElement, Datum, PElement, PDatum>): Selection<GElement, Datum, PElement, PDatum>

I looked through the advanced types documentation but could not understand what these types mean. I can't say if they are a Selection type with these subtypes or whatever.


Solution

  • Those are generics. And put simply they let you parameterize a type, allowing you pass other types into it.

    So to use your example, you could do something like:

    interface SomeType<T, U, V> {
      t: T
      u: U
      v: V
    }
    
    const foo: SomeType<string, number, { cool: boolean }> = {
      //                T       U       V
      t: 'a string',
      u: 123,
      v: { cool: true }
    }
    

    Playground

    Lots of documentation on generics here: https://www.typescriptlang.org/docs/handbook/generics.html