I am trying to do something I am not sure is possible in TypeScript: inferring the argument types/return types from a function.
For example:
function foo(a: string, b: number) { return `${a}, ${b}`; } type typeA = <insert magic here> foo; // Somehow, typeA should be string; type typeB = <insert magic here> foo; // Somehow, typeB should be number;
My use case is to try to create a config object that contains constructors and parameters.
For example:
interface IConfigObject<T> { // Need a way to compute type U based off of T. TypeConstructor: new(a: U): T; constructorOptions: U; } // In an ideal world, could infer all of this from TypeConstructor class fizz { constructor(a: number) {} } const configObj : IConfigObj = { TypeConstructor: fizz; constructorOptions: 13; // This should be fine } const configObj2 : IConfigObj = { TypeConstructor: fizz; constructorOptions: 'buzz'; // Should be a type error, since fizz takes in a number }
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
Use the ConstructorParameters utility type to get the parameters type of a class constructor in TypeScript, e.g. type T = ConstructorParameters<typeof MyClass> . The ConstructorParameters type returns a tuple type containing the parameter types of the constructor function.
It is used to prevent a specific constructor from being called implicitly when constructing an object. For example, without the explicit keyword, the following code is valid C++: Array a = 10; This will call the Array single-argument constructor with the integer argument of 10.
This method takes four arguments: the loan amount, the interest rate, the future value and the number of periods.
Typescript now has the ConstructorParameters
builtin, similar to the Parameters
builtin. Make sure you pass the class type, not the instance:
ConstructorParameters<typeof SomeClass>
ConstructorParameter Official Doc
Parameters Official Doc
With TypeScript 2.8 you can use the new extends
keyword:
type FirstArgument<T> = T extends (arg1: infer U, ...args: any[]) => any ? U : any; type SecondArgument<T> = T extends (arg1: any, arg2: infer U, ...args: any[]) => any ? U : any; let arg1: FirstArgument<typeof foo>; // string; let arg2: SecondArgument<typeof foo>; // number; let ret: ReturnType<typeof foo>; // string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With