获取函数/类构造函数的参数类型 [英] Get argument types for function / class constructor

查看:49
本文介绍了获取函数/类构造函数的参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些我不确定在 TypeScript 中是否可行的事情:从函数推断参数类型/返回类型.

I am trying to do something I am not sure is possible in TypeScript: inferring the argument types/return types from a function.

例如:

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.

例如:

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
}

推荐答案

在 TypeScript 2.8 中,您可以使用新的 extends 关键字:

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;

这篇关于获取函数/类构造函数的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆