TypeScript generic type and default function application

I have the following TS code:

export interface Id<T> {
  (arg: T): T;
}

export function IdFunc<T>(arg: T): T {
  return arg;
}

I want to use the Id and IdFunc like so to provide a default implementation of transformer.

interface Options {
  transformer: Id<number>;
}

const defaultOptions : Options = {
  transformer: IdFunc<number>
               ^^^ Type 'number' is not assignable to type 'Id<number>'
}

But I get an error when doing this, is there a way to accomplish using function name + type for the default option without doing something like this:

const myIdentity: Id<number> = IdFunc;

const defaultOptions : Options = {
  transformer: myIdentity
}

Playground link

19 thoughts on “TypeScript generic type and default function application”

  1. function IdFunc is a function which takes an argument of type T and returns a value of the same type T. It is a generic function, so it can be called with any value.

    The interface Id<T> defines a function which is not generic. The interface itself is generic, but Id<number> defines a non-generic function that looks like (arg: number) => number.

    It is perfectly fine to create your Options by including the generic IdFunc as your transformer. When called with a number it will return a number, so it is assignable to Id<number>

    const defaultOptions : Options = {
      transformer: IdFunc,
    }
    

    You cannot use IdFunc<number> as a value because the generic is set when the function is called. It’s not something that you can set beforehand (at least with this current signature). You will get an error "number only refers to a type, but is being used as a value here."

    Typescript Playground Link

    Reply

Leave a Comment