简体   繁体   中英

TypeScript: Inferring function arguments from a constructor signature

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM