我正在尝试做我不确定在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
}
有人可以帮我吗?谢谢!
使用TypeScript 2.8,您可以使用新的extends
关键字:
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;
对于提取构造函数参数类型的用例,我将给出更直接的答案。
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]
添加了打字稿2.8 conditional types with type inference
添加了TypeScript 3.0 rest-elements-in-tuple-types,因此您现在就可以获取Array
类型的所有参数。
type ArgumentsType<T extends (...args: any[]) => any> = 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;
}
Typescript现在具有ConstructorParameters
内置,类似于Parameters
内置。确保您传递的是类类型,而不是实例:
ConstructorParameters<typeof SomeClass>
这种方法怎么样:
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
您可以有一个索引类型变量:
const configs: { [name: string]: IConfigObject<any, any> } = {
config1: createConfig(fizz, 3),
config2: createConfig(fizz, "str"), // error
config3: createConfig(buzz, "str")
}