获取函数/类构造函数的参数类型

时间:2017-04-18 20:21:52

标签: typescript

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

例如

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;

我的用例是尝试创建一个包含构造函数和参数的配置对象:

例如:

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
}

任何人都可以帮助我吗?谢谢!

5 个答案:

答案 0 :(得分:19)

使用TypeScript 2.8,您可以使用新的keywords <- c("Keyword1", "Keyword2", "Keyword3") df <- read.table(text="Title Abstract 'Rstudio Keyword1' 'A interesting program language keyword2' 'Python Keyword2' 'A interesting program keyword3 language'",h=T,strin=F) 关键字:

extends

答案 1 :(得分:8)

添加了打字稿2.8 conditional types with type inference

添加了rest-elements-in-tuple-types的Typescript 3.0,因此您现在可以获取Array类型的所有参数。

type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;

type Func = (a: number, b: string) => boolean;
type Args = ArgumentsType<Func> // type Args = [number, string];
type Ret = ReturnType<Func> // type Ret = boolean;

您可以像这样使用它:

const func = (...args: Args): Ret => { // type the rest parameters and return type
  const [a, b] = args; // spread the arguments into their names
  console.log(a, b); // use the arguments like normal
  return true;
};

// Above is equivalent to:
const func: Func = (a, b) => {
  console.log(a, b);
  return true;
}

答案 2 :(得分:5)

对于提取构造函数参数类型的用例,我将给出一个更直接的答案。

type GetConstructorArgs<T> = T extends new (...args: infer U) => any ? U : never

class Foo {
    constructor(foo: string, bar: number){
        //
    }
}

type FooConstructorArgs = GetConstructorArgs<typeof Foo> // [string, number]

答案 3 :(得分:2)

这种方法怎么样:

pyrcc5

code in playground

修改

您可以拥有索引类型变量:

interface IConfigObject<T, U> {
    TypeConstructor: new(a: U) => T;
    constructorOptions: U;
}

class fizz {
    constructor(a: number) {}
}

function createConfig<U, T>(cls: { new (arg: U): T }, arg: U): IConfigObject<T, U> {
    return {
        TypeConstructor: cls,
        constructorOptions: arg
    }
}

const configObj = createConfig(fizz, 3); // ok
const configObj2 = createConfig(fizz, "str"); // error

答案 4 :(得分:1)

Typescript现在具有ConstructorParameters内置功能,类似于Parameters内置功能。确保您传递的是类类型,而不是实例:

ConstructorParameters<typeof SomeClass>
相关问题