我正在尝试做一些我不确定在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;
Run Code Online (Sandbox Code Playgroud)
我的用例是尝试创建一个包含构造函数和参数的配置对象:
例如:
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) {} …Run Code Online (Sandbox Code Playgroud) ReturnType<T> 提取函数的返回类型.
有没有办法定义ArgumentsType<T>以tuple格式提取函数的参数类型?
例如,
ArgumentsType<(a: number, b: string) => boolean>会的[number, string].
我正在尝试输入正在使用的提取程序组件API。这个想法很简单,给它一个fetcher(承诺返回函数)和一个params数组(代表位置参数)作为道具,它将结果提供给渲染道具。
type FunctionType<A extends any[] = any[], R = any> = (...args: A) => R
type Arguments<T> = T extends FunctionType<infer R, any> ? R : never
type PromiseReturnType<T> = T extends (...args: any[]) => Promise<infer R>
? R
: never
type ChildrenProps<F> = {
data: PromiseReturnType<F>
}
type Props<F> = {
fetcher: F
params: Arguments<F>
children: (props: ChildrenProps<F>) => React.ReactNode
}
class Fetch<F> extends React.Component<Props<F>> {
render() {
return null
}
}
const usage = …Run Code Online (Sandbox Code Playgroud) 我们使用的模块不会导出其所有参数的类型。这意味着参数经过类型检查,但我们不能在方法调用之前定义所需类型的变量。
例子:
// library
interface Internal { foo(): number } // I want to have a name for this un-exported interface
class A {
bar(s: string, x: Internal): string {
return s + x.foo(); // whatever
}
}
export const Exported = A;
Run Code Online (Sandbox Code Playgroud)
使用时Exported.bar有没有办法让我首先定义参数以便正确输入?
let e = new Exported();
let x : /*???*/;
e.bar("any ideas?", x);
Run Code Online (Sandbox Code Playgroud)
我想到了一种使用泛型来创建null类型的方法,Internal这样我就可以给出x正确的类型,但这很笨拙,有没有办法在type定义中捕获这种类型并更干净地使用它?
function deduce<T>(f: (s: string, t: T) => any): T {
return null;
} …Run Code Online (Sandbox Code Playgroud)