0

As a tool for composability, I have a function that takes a class constructor argument and returns a function that uses the arguments it is passed to construct an instance of the class I initially passed in.

class Thing {
  constructor (metadata) { this.metadata = metadata; }
}

const A = (C) => (...a) => new C(...a);
const X = A(Thing);

When I hover over X, I want it to tell me that the function signature is essentially (metadata) => Thing. Instead, it says that the signature of X is (...a) => any. What annotations are required in order to get TypeScript (latest version) to infer the signature of X correctly?

1 Answer 1

4
const A = <T extends unknown[], K>(C: new (...args: T) => K) => (...args: T) => new C(...args);

Playground link

Breaking it down, we have a T array type, and we annotate C to have a constructor (using the new keyword) that takes in the args denoted by T, and returns a value K. We then return a function that essentially undoes the constructor.

As a side note, please compile with --noImplicitAny; it'll give you helpful warnings for things like this where arguments have an any type due to not specifying their type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.