参数列表前的 'new' 关键字在打字稿箭头函数中意味着什么?
What does the 'new' keyword before the parameter list mean in a typscript arrow function?
我对 TypeScript 还是很陌生,甚至 JavaScript。我一直在努力思考微软的一个例子,关于如何将 AzureAD 身份验证集成到 React 应用程序中。该示例使用 HOC 为组件提供身份验证。 HOC 的声明如下所示:
function withAuthProvider<T extends React.Component<AuthComponentProps>>(
WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}
大部分还是比较清楚的。令我困惑的是 WrappedComponent
的类型。具体来说,我不明白 new
关键字在该上下文中的作用。
谁能帮帮我?
这是一个构造函数类型。这意味着当你用 new
调用它时,你可以给它一个 props
参数和一个可选的 context
参数,它会构造一个 T
类型的实例。
这是一个例子:
class Foo {
private value: number;
constructor(x: number, y: number = 1) {
this.value = x + y;
}
}
const foo: new (arg1: number, arg2?: number) => Foo = Foo;
// can be invoked like this (with new)
const x1: Foo = new foo(1);
const x2: Foo = new foo(1, 2);
// cannot be invoked without new
// these lines will error at both compile- and run-time
const y1: Foo = foo(1);
const y2: Foo = foo(1, 2);
我对 TypeScript 还是很陌生,甚至 JavaScript。我一直在努力思考微软的一个例子,关于如何将 AzureAD 身份验证集成到 React 应用程序中。该示例使用 HOC 为组件提供身份验证。 HOC 的声明如下所示:
function withAuthProvider<T extends React.Component<AuthComponentProps>>(
WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}
大部分还是比较清楚的。令我困惑的是 WrappedComponent
的类型。具体来说,我不明白 new
关键字在该上下文中的作用。
谁能帮帮我?
这是一个构造函数类型。这意味着当你用 new
调用它时,你可以给它一个 props
参数和一个可选的 context
参数,它会构造一个 T
类型的实例。
这是一个例子:
class Foo {
private value: number;
constructor(x: number, y: number = 1) {
this.value = x + y;
}
}
const foo: new (arg1: number, arg2?: number) => Foo = Foo;
// can be invoked like this (with new)
const x1: Foo = new foo(1);
const x2: Foo = new foo(1, 2);
// cannot be invoked without new
// these lines will error at both compile- and run-time
const y1: Foo = foo(1);
const y2: Foo = foo(1, 2);